如何使用 jQuery 获取元素的 ID?

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

How can I get the ID of an element using jQuery?

jqueryjquery-selectors

提问by fearofawhackplanet

<div id="test"></div>
<script>
  $(document).ready(function() {
    alert($('#test').id);
  });  
</script>

Why doesn't the above work, and how should I do this?

为什么上述方法不起作用,我该怎么做?

回答by instanceof me

The jQuery way:

jQuery方式:

$('#test').attr('id')

In your example:

在你的例子中:

$(document).ready(function() {
  console.log($('#test').attr('id'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"></div>

Or through the DOM:

或者通过 DOM:

$('#test').get(0).id;

or even :

甚至 :

$('#test')[0].id;

and reason behind usage of $('#test').get(0)in JQuery or even $('#test')[0]is that $('#test')is a JQuery selector and returns an array() of resultsnot a single element by its default functionality

$('#test').get(0)在 JQuery 中使用的原因甚至$('#test')[0]是它$('#test')是一个 JQuery 选择器并返回一个结果数组()而不是其默认功能的单个元素

an alternative for DOM selector in jquery is

jquery 中 DOM 选择器的另一种选择是

$('#test').prop('id')

which is different from .attr()and $('#test').prop('foo')grabs the specified DOM fooproperty, while $('#test').attr('foo')grabs the specified HTML fooattribute and you can find more details about differences here.

它不同于.attr()$('#test').prop('foo')抓取指定的 DOMfoo属性,而$('#test').attr('foo')抓取指定的 HTMLfoo属性,您可以在此处找到有关差异的更多详细信息。

回答by Steven

$('selector').attr('id')will return the id of the first matched element. Reference.

$('selector').attr('id')将返回第一个匹配元素的 id。参考

If your matched set contains more than one element, you can use the conventional .eachiteratorto return an array containing each of the ids:

如果您的匹配集合包含多个元素,您可以使用传统.each迭代器返回一个包含每个 id 的数组:

var retval = []
$('selector').each(function(){
  retval.push($(this).attr('id'))
})
return retval

Or, if you're willing to get a little grittier, you can avoid the wrapper and use the .mapshortcut.

或者,如果您愿意变得更加坚韧,则可以避免使用包装器并使用.map快捷方式

return $('.selector').map(function(index,dom){return dom.id})

回答by Anurag

idis a property of an html Element. However, when you write $("#something"), it returns a jQuery object that wraps the matching DOM element(s). To get the first matching DOM element back, call get(0)

id是 html 的属性Element。但是,当您编写 时$("#something"),它会返回一个包含匹配 DOM 元素的 jQuery 对象。要取回第一个匹配的 DOM 元素,请调用get(0)

$("#test").get(0)

On this native element, you can call id, or any other native DOM property or function.

在这个原生元素上,您可以调用 id 或任何其他原生 DOM 属性或函数。

$("#test").get(0).id

That's the reason why idisn't working in your code.

这就是为什么id在您的代码中不起作用的原因。

Alternatively, use jQuery's attrmethod as other answers suggest to get the idattribute of the first matching element.

或者,使用 jQuery 的attr方法作为其他答案建议获取id第一个匹配元素的属性。

$("#test").attr("id")

回答by Chris

Above answers are great, but as jquery evolves.. so you can also do:

上面的答案很好,但随着 jquery 的发展......所以你也可以这样做:

var myId = $("#test").prop("id");

回答by stat

$.fn.extend({
    id : function() {
        return this.attr('id');
    }
});

alert( $('#element').id() );

Some checking code required of course, but easily implemented!

当然需要一些检查代码,但很容易实现!

回答by Joey C.

.idis not a valid jquery function. You need to use the .attr()function to access attributes an element possesses. You can use .attr()to both change an attribute value by specifying two parameters, or get the value by specifying one.

.id不是有效的 jquery 函数。您需要使用该.attr()函数来访问元素拥有的属性。.attr()既可以通过指定两个参数来更改属性值,也可以通过指定一个参数来获取值。

http://api.jquery.com/attr/

http://api.jquery.com/attr/

回答by Jay Query

If you want to get an ID of an element, let's say by a class selector, when an event (in this case click event) was fired on that specific element, then the following will do the job:

如果你想获得一个元素的 ID,让我们说一个类选择器,当一个事件(在这种情况下是点击事件)在该特定元素上被触发时,那么以下将完成这项工作:

 $('.your-selector').click(function(){
       var id = $(this).attr('id');
 });

回答by Kumar

$('#test').attr('id')In your example:

$('#test').attr('id')在你的例子中:

<div id="test"></div>

$(document).ready(function() {
    alert($('#test').attr('id'));
}); 

回答by GoldBishop

Well, seems there has not been a solution and would like to propose my own solution that is an expansion of the JQuery prototype's. I put this in a Helper file that is loaded after the JQuery library, hence the check for window.jQuery

好吧,似乎还没有解决方案,我想提出我自己的解决方案,即 JQuery 原型的扩展。我把它放在一个在 JQuery 库之后加载的 Helper 文件中,因此检查window.jQuery

if (window.jQuery) {
    $.prototype.id = function () {
        if (this.length > 1) {
            var val = [];
            this.each(function (idx, el) {
                val.push($(el).id());
            });
            return val;
        } else {
            return this.attr('id');
        }
    }
}

It may not be perfect but it is a start to maybe getting inclusion into the JQuery library.

它可能并不完美,但它是可能被包含到 JQuery 库中的开始。

Returns either a single string value or an Array of string values. The Array of string values, is for the event an multi-element selector was used.

返回单个字符串值或字符串值数组。字符串值数组用于使用多元素选择器的事件。

回答by GoldBishop

$('#test')returns a jQuery object, so you can't use simply object.idto get its Id

$('#test')返回一个 jQuery 对象,所以你不能简单object.id地使用它来获取它Id

you need to use $('#test').attr('id'), which returns your required IDof the element

你需要使用$('#test').attr('id'),它返回你需要ID的元素

This can also be done as follows ,

这也可以如下完成,

$('#test').get(0).idwhich is equal to document.getElementById('test').id

$('#test').get(0).id这等于 document.getElementById('test').id