如何使用jQuery获取元素的ID? [英] How can I get the ID of an element using jQuery?
问题描述
<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
为什么上面的方法不起作用,我应该怎么做?
Why doesn't the above work, and how should I do this?
推荐答案
jQuery方式:
$('#test').attr('id')
在您的示例中:
$(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>
或通过DOM:
$('#test').get(0).id;
甚至:
$('#test')[0].id;
以及在JQuery甚至$('#test')[0]
中使用$('#test').get(0)
的原因是$('#test')
是JQuery选择器,并且返回结果的array()并不是其默认功能的单个元素
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 results not a single element by its default functionality
jquery中DOM选择器的替代方法是
an alternative for DOM selector in jquery is
$('#test').prop('id')
与.attr()
和$('#test').prop('foo')
不同的
抓住了指定的DOM foo
属性,而$('#test').attr('foo')
抓住了指定的HTML foo
属性,您可以找到有关差异的更多详细信息
which is different from .attr()
and $('#test').prop('foo')
grabs the specified DOM foo
property, while $('#test').attr('foo')
grabs the specified HTML foo
attribute and you can find more details about differences here.
这篇关于如何使用jQuery获取元素的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!