<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
为什么上面的方法不起作用,我应该怎么做?
<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');
=========================
其他回答
这将最终解决您的问题:
假设您在一个页面上有多个按钮,您希望根据其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并进行了修改。
可能对找到此线程的其他人有用。只有当您已经使用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();
这可以是元素id、类,也可以自动使用
------------------------
$(this).attr('id');
=========================
------------------------
$("a.remove[data-id='2']").attr('id');
=========================
------------------------
$("#abc1'").attr('id');
=========================
以上答案很好,但随着jquery的发展。。因此,您还可以执行以下操作:
var myId = $("#test").prop("id");
重要提示:如果要使用jQuery创建新对象并绑定事件,则必须使用prop而不是attr,如下所示:
$(“<div/>”,{id:“yourId”,class:“yourClass”,html:“<span></span>”}).on(“单击”,函数(e){alert($(this).prop(“id”);}).appendTo(“#something”);