如何使用 jQuery 获取元素的 ID? [英] How can I get the ID of an element using jQuery?
问题描述
<脚本>$(document).ready(function() {警报($('#test').id);});
为什么上述方法不起作用,我该怎么做?
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 选择器,返回一个结果数组,它的默认功能不是单个元素
jQuery 中 DOM 选择器的替代方案是
$('#test').prop('id')
不同于 .attr()
和 $('#test').prop('foo')
抓取指定的 DOM foo
属性,而 $('#test').attr('foo')
抓取指定的 HTML foo
属性,您可以找到有关差异的更多详细信息 这里.
<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
Why doesn't the above work, and how should I do this?
The jQuery way:
$('#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:
$('#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 results not a single element by its default functionality
an alternative for DOM selector in jquery is
$('#test').prop('id')
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屋!