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

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


当前回答

这是一个老问题,但截至2015年,这可能会奏效:

$('#test').id;

您还可以分配任务:

$('#test').id = "abc";

只要定义以下JQuery插件:

Object.defineProperty($.fn, 'id', {
    get: function () { return this.attr("id"); },
    set: function (newValue) { this.attr("id", newValue); }
});

有趣的是,如果元素是DOM元素,那么:

element.id === $(element).id; // Is true!

其他回答

$('tagname').attr('id');

使用上面的代码,您可以获得id。

$('#test').attr('id')在您的示例中:

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

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

jQuery方法:

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

在您的示例中:

$(文档).ready(函数){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”).get(0)或甚至$(“#test”)[0]的原因是$(“#test”)是JQuery选择器,并返回结果的array(),而不是其默认功能中的单个元素

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

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

它不同于.attr()和$('#test').prop('o')获取指定的DOM foo属性,而$('#test').attr“'o'”获取指定的HTML foo属性。

它不会回答OP,但对其他人来说可能很有趣:在这种情况下,您可以访问.id字段:

$('#drop-insert').map((i, o) => o.id)

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

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