Javascript 使用名称 jquery 通过索引获取 id 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10964378/
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-24 03:48:05  来源:igfitidea点击:

get id value by index using name jquery

javascriptjqueryhtml

提问by Shahid Ghafoor

html

html

<input id="1" name="myText" type="text" value="20"/>
<input id="2" name="myText" type="text" value="30"/>
<input id="3" name="myText" type="text" value="40"/>

How can I get id value by indexusing name?

如何index使用名称获取 id 值?

The following code snippet is not working

以下代码片段不起作用

var getVal = $('[name="myText"]').index(1);

回答by gdoron is supporting Monica

jQuery holds the DOM elements in the set like an array so you can use the indexes operator([]) to get the element, or get the jQuery object that wraps the desired element with :eq(n)`.eq(n)`

jQuery 将 DOM 元素像数组一样保存在集合中,因此您可以使用索引 operator( []) 来获取元素,或者获取用:eq(n)`.eq(n)`包装所需元素的 jQuery 对象

$('input[name="myText"]:eq(1)').attr('id')

You should mention what to you consider to be index(1)the first or the second:

您应该提及您认为是index(1)第一个或第二个的内容:

$('input[name="myText"]:eq(0)').attr('id') // First
$('input[name="myText"]:eq(1)').attr('id') // Second

Or:

或者:

$('input[name="myText"]')[0].id // First

回答by tvanfosson

If you want the first value, you can filter and use the attrmethod to get the value of the id attribute.

如果你想要第一个值,你可以过滤并使用该attr方法来获取 id 属性的值。

var getVal = $('[name="myText"]:first').attr('id'); // first id

If you want some other element, you can use eqand choose the zero-based element in the collection.

如果需要其他元素,可以使用eq并选择集合中的从零开始的元素。

var getVal = $('[name="myText"]:eq(1)').attr('id'); // second id

回答by moribvndvs

My answer refers to accessing elements in the jQuery result object by index. You can use selectors such as :eqindicated in other answers.

我的回答是指通过索引访问 jQuery 结果对象中的元素。您可以使用:eq其他答案中指示的选择器。

However, you can use .get(1)instead of your index.

但是,您可以使用.get(1)代替您的index.

var id = $('[name="myText"]').get(1).id;

Is equivalent to

相当于

var id = $('[name="myText"]:eq(1)').attr('id');

Example: http://jsfiddle.net/HackedByChinese/UmKw6/1/

示例:http: //jsfiddle.net/HackedByChinese/UmKw6/1/

The second method is the preferred route, since it means you never leave the jQueryresult object and thus can chain other jQuery calls in one statement.

第二种方法是首选方法,因为它意味着您永远不会离开jQuery结果对象,因此可以在一个语句中链接其他 jQuery 调用。

var id = $('[name="myText"]:eq(1)').css('color', 'red').attr('id'); // example of chaining jQuery methods. sets the text color to red and then returns the id.