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

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


当前回答

这可以是元素id、类,也可以自动使用

------------------------
$(this).attr('id');
=========================
------------------------
$("a.remove[data-id='2']").attr('id');
=========================
------------------------
$("#abc1'").attr('id');
=========================

其他回答

以上答案很好,但随着jquery的发展。。因此,您还可以执行以下操作:

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

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

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

$(“#按钮”).click(函数){var clickID=$(“#testDiv”).attr(“id”);console.log(clickID)});<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><div id=“testDiv”>单击按钮时,您将获得该id值</div><button id=“button”>按钮</button>

嗯,似乎还没有解决方案,我想提出我自己的解决方案,这是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库的一个开始。

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

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

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

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