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

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


当前回答

$.fn.extend({
    id : function() {
        return this.attr('id');
    }
});

alert( $('#element').id() );

当然需要一些检查代码,但很容易实现!

其他回答

id是html元素的属性。然而,当您编写$(“#something”)时,它返回一个jQuery对象,该对象包装匹配的DOM元素。要获取第一个匹配的DOM元素,请调用get(0)

$("#test").get(0)

在本机元素上,可以调用id或任何其他本机DOM属性或函数。

$("#test").get(0).id

这就是id在代码中不起作用的原因。

或者,按照其他答案的建议,使用jQuery的attr方法来获取第一个匹配元素的id属性。

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

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

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

$('#test')返回一个jQuery对象,因此不能简单地使用object.id获取其id

您需要使用$('#test').attr('id'),它返回元素所需的id

这也可以如下进行,

$('#test').get(0).id,等于document.getElementById('test').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库的一个开始。

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

可能对找到此线程的其他人有用。只有当您已经使用jQuery时,下面的代码才有效。函数始终返回一个标识符。如果元素没有标识符,函数将生成标识符并将其附加到元素。

var generatedIdCounter = 0;

$.fn.id = function() {
    var identifier = this.attr('id');

    if(!identifier) {
        generatedIdCounter++;
        identifier = 'isGenerated_' + generatedIdCounter;

        this.attr('id', identifier);
    }

    return identifier;
}

如何使用:

$('.classname').id();

$('#elementId').id();