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

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


当前回答

重要提示:如果要使用jQuery创建新对象并绑定事件,则必须使用prop而不是attr,如下所示:

$(“<div/>”,{id:“yourId”,class:“yourClass”,html:“<span></span>”}).on(“单击”,函数(e){alert($(this).prop(“id”);}).appendTo(“#something”);

其他回答

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

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

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

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

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

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

$("#test").attr("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库的一个开始。

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

这是一个老问题,但截至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!

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

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

这也可以如下进行,

$('#test').get(0).id,等于document.getElementById('test').id

这将最终解决您的问题:

假设您在一个页面上有多个按钮,您希望根据其ID使用jQueryAjax(或不是Ajax)更改其中一个按钮。

还可以说,您有许多不同类型的按钮(用于表单、审批和类似目的),您希望jQuery只处理“类似”按钮。

这是一个有效的代码:jQuery将只处理.cls-hlpb类的按钮,它将获取所单击按钮的id并将根据来自ajax的数据进行更改。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">    </script>
<script>
$(document).ready(function(){
$(".clshlpbtn").on('click',function(e){
var id = $(e.target).attr('id');
 alert("The id of the button that was clicked: "+id);
$.post("demo_test_post.asp",
    {
      name: "Donald Duck",
      city: "Duckburg"
    },
    function(data,status){

    //parsing the data should come here:
    //var obj = jQuery.parseJSON(data);
    //$("#"+id).val(obj.name);
    //etc.

    if (id=="btnhlp-1")
       $("#"+id).attr("style","color:red");
    $("#"+id).val(data);
    });
});




});
</script>
</head>
<body>

<input type="button" class="clshlpbtn" id="btnhlp-1" value="first btn">    </input>
<br />
<input type="button" class="clshlpbtn" id="btnhlp-2" value="second btn">    </input>
<br />
<input type="button" class="clshlpbtn" id="btnhlp-9" value="ninth btn">    </input>

</body>
</html>

代码取自w3schools并进行了修改。