jQuery jquery查找类并获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5287736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:54:06  来源:igfitidea点击:

jquery find class and get the value

jqueryjquery-selectors

提问by Jason

I am trying to get the value of an input text field.

我正在尝试获取输入文本字段的值。

the HTML is:

HTML是:

<div id="start">
    <p>
        <input type="text" class="myClass" value="my value" name="mytext"/>
    </p>
</div>

The jquery is:

jQuery 是:

var myVar = $("#start").find('.myClass').val();

The problem is that myVar is coming up undefined. Does anyone know why?

问题是 myVar 未定义。有谁知道为什么?

回答by BoltClock

Class selectors are prefixed with a dot. Your .find()is missing that so jQuery thinks you're looking for <myClass>elements.

类选择器以点为前缀。您.find()缺少它,因此 jQuery 认为您正在寻找<myClass>元素。

var myVar = $("#start").find('.myClass').val();

回答by user2907730

var myVar = $("#start").find('.myClass').first().val();

回答by DuckMaestro

var myVar = $("#start").find('myClass').val();

var myVar = $("#start").find('myClass').val();

needs to be

需要是

var myVar = $("#start").find('.myClass').val();

var myVar = $("#start").find('.myClass').val();

Remember the CSS selector rules require "." if selecting by class name. The absence of "." is interpreted to mean searching for <myclass></myclass>.

记住 CSS 选择器规则需要“.”。如果按类名选择。的缺席 ”。” 被解释为意味着搜索<myclass></myclass>

回答by sandeep kumar

You can get value of id,name or value in this way. class name my_class

您可以通过这种方式获取 id、name 或 value 的值。类名 my_class

 var id_value = $('.my_class').$(this).attr('id'); //get id value
 var name_value = $('.my_class').$(this).attr('name'); //get name value
 var value = $('.my_class').$(this).attr('value'); //get value any input or tag

回答by Soura Sankar Ghosh

You can also get the value by the following way

您还可以通过以下方式获取值

$(document).ready(function(){
  $("#start").click(function(){
    alert($(this).find("input[class='myClass']").val());
  });
});