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

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


当前回答

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

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

其他回答

这将最终解决您的问题:

假设您在一个页面上有多个按钮,您希望根据其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并进行了修改。

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

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

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

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

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

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

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

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

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

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

由于id是一个属性,您可以使用attr方法获取它。

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

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

这也可以如下进行,

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