<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
为什么上面的方法不起作用,我应该怎么做?
<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
为什么上面的方法不起作用,我应该怎么做?
当前回答
$('#test').attr('id')在您的示例中:
<div id="test"></div>
$(document).ready(function() {
alert($('#test').attr('id'));
});
其他回答
可能对找到此线程的其他人有用。只有当您已经使用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使用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原型的扩展。我将其放在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方法:
$('#test').attr('id')
在您的示例中:
$(文档).ready(函数){console.log($('#test').attr('id'));});<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><div id=“test”></div>
或者通过DOM:
$('#test').get(0).id;
或甚至:
$('#test')[0].id;
在JQuery中使用$(“#test”).get(0)或甚至$(“#test”)[0]的原因是$(“#test”)是JQuery选择器,并返回结果的array(),而不是其默认功能中的单个元素
jquery中DOM选择器的另一种选择是
$('#test').prop('id')
它不同于.attr()和$('#test').prop('o')获取指定的DOM foo属性,而$('#test').attr“'o'”获取指定的HTML foo属性。
$.fn.extend({
id : function() {
return this.attr('id');
}
});
alert( $('#element').id() );
当然需要一些检查代码,但很容易实现!