<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
为什么上面的方法不起作用,我应该怎么做?
<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
为什么上面的方法不起作用,我应该怎么做?
当前回答
$('#test')返回一个jQuery对象,因此不能简单地使用object.id获取其id
您需要使用$('#test').attr('id'),它返回元素所需的id
这也可以如下进行,
$('#test').get(0).id,等于document.getElementById('test').id
其他回答
$('#test')返回一个jQuery对象,因此不能简单地使用object.id获取其id
您需要使用$('#test').attr('id'),它返回元素所需的id
这也可以如下进行,
$('#test').get(0).id,等于document.getElementById('test').id
它不会回答OP,但对其他人来说可能很有趣:在这种情况下,您可以访问.id字段:
$('#drop-insert').map((i, o) => o.id)
嗯,似乎还没有解决方案,我想提出我自己的解决方案,这是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');
}
}
}
它可能并不完美,但它可能是JQuery库的一个开始。
返回单个字符串值或字符串值数组。字符串值数组用于使用多元素选择器的事件。
$('tagname').attr('id');
使用上面的代码,您可以获得id。
$.fn.extend({
id : function() {
return this.attr('id');
}
});
alert( $('#element').id() );
当然需要一些检查代码,但很容易实现!