如何使用 jQuery 获取元素的名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8852665/
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
How can I get name of element with jQuery?
提问by Poonam Bhatt
How can I get name property of HTML element with jQuery?
如何使用 jQuery 获取 HTML 元素的 name 属性?
回答by Nicola Peluchetti
You should use attr('name')
like this
你应该attr('name')
像这样使用
$('#yourid').attr('name')
you should use an id selector, if you use a class selector you encounter problems because a collection is returned
你应该使用 id 选择器,如果你使用类选择器,你会遇到问题,因为返回了一个集合
回答by Poonam Bhatt
To read a property of an object you use .propertyName
or ["propertyName"]
notation.
读取您使用的对象的属性.propertyName
或["propertyName"]
符号。
This is no different for elements.
这对于元素没有什么不同。
var name = $('#item')[0].name;
var name = $('#item')[0]["name"];
If you specifically want to use jQuery
methods, then you'd use the .prop()
method.
如果您特别想使用jQuery
方法,那么您将使用该.prop()
方法。
var name = $('#item').prop('name');
Please note that attributes and properties are not necessarily the same.
请注意,attributes 和properties 不一定相同。
回答by Patricia
$('someSelectorForTheElement').attr('name');
回答by rjb
Play around with this jsFiddle example:
HTML:
HTML:
<p id="foo" name="bar">Hello, world!</p>
jQuery:
jQuery:
$(function() {
var name = $('#foo').attr('name');
alert(name);
console.log(name);
});
This uses jQuery's .attr()method to get value for the first element in the matched set.
这使用 jQuery 的.attr()方法来获取匹配集合中第一个元素的值。
While not specifically jQuery, the result is shown as an alert promptand written to the browser's console.
回答by Dennis Traub
var name = $('#myElement').attr('name');