如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:09:44  来源:igfitidea点击:

How can I get name of element with jQuery?

jqueryhtml

提问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 .propertyNameor ["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 jQuerymethods, 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:

试试这个jsFiddle 示例

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.

虽然不是专门的 jQuery,但结果显示为警告提示并写入浏览器的控制台

回答by Dennis Traub

var name = $('#myElement').attr('name');

回答by Didier Ghys

The method .attr()allows getting attribute value of the first element in a jQuery object:

.attr()方法允许获取 jQuery 对象中第一个元素的属性值:

$('#myelement').attr('name');