$(document).ready(function() {
alert($('#test').id);
});
为什么上述方法不起作用,我应该怎么做?
#1楼
$('tagname').attr('id');
使用上面的代码,您可以获得ID。
#2楼
以上答案很好,但是随着jquery的发展..您也可以这样做:
var myId = $("#test").prop("id");
#3楼
$.fn.extend({
id : function() {
return this.attr('id');
}
});
alert( $('#element').id() );
当然需要一些检查代码,但是很容易实现!
#4楼
如果要获取某个元素的ID,则由类选择器说,当在该特定元素上触发一个事件(在本例中为click事件)时,将执行以下操作:
$('.your-selector').click(function(){
var id = $(this).attr('id');
});
#5楼
重要提示:如果要使用jQuery创建新对象并绑定事件,则必须使用prop而不是attr ,如下所示:
$("
",{ id: "yourId", class: "yourClass", html: "" }).on("click", function(e) { alert($(this).prop("id")); }).appendTo("#something");#6楼
这可以是元素id,class,也可以自动使用甚至
------------------------
$(this).attr('id');
=========================
------------------------
$("a.remove[data-id='2']").attr('id');
=========================
------------------------
$("#abc1'").attr('id');
=========================
#7楼
这最终将解决您的问题:
假设您在页面上有许多按钮,并且您想根据其ID使用jQuery Ajax(或不使用ajax)更改其中一个按钮。
还可以说您有许多不同类型的按钮(用于表单,用于批准和用于类似目的),并且您希望jQuery只处理“喜欢”按钮。
这是一个有效的代码:jQuery将仅处理.cls-hlpb类的按钮,它将获取被单击的按钮的ID,并将根据来自Ajax的数据对其进行更改。
$(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);
});
});
});
代码取自w3schools,并已更改。
#8楼
jQuery方式:
$('#test').attr('id')
在您的示例中:
$(document).ready(function() { console.log($('#test').attr('id')); });
或通过DOM:
$('#test').get(0).id;
甚至 :
$('#test')[0].id;
在JQuery甚至$('#test')[0]使用$('#test').get(0)是$('#test')是一个JQuery选择器并返回array()结果的功能不是单个元素
jQuery中DOM选择器的替代方法是
$('#test').prop('id')
这与.attr()和$('#test').prop('foo') ,它获取指定的DOM foo属性,而$('#test').attr('foo')获取指定的HTML foo属性,您可以在此处找到有关差异的更多详细信息。
#9楼
$('selector').attr('id')将返回第一个匹配元素的ID。 参考 。
如果匹配的集合包含多个元素,则可以使用常规的.each 迭代器返回包含每个id的数组:
var retval = []
$('selector').each(function(){
retval.push($(this).attr('id'))
})
return retval
或者,如果您愿意加一点勇气,可以避免使用包装器,而可以使用.map 快捷方式 。
return $('.selector').map(function(index,dom){return dom.id})
#10楼
$('#test')返回一个jQuery对象,因此不能简单地使用object.id来获取其Id
您需要使用$('#test').attr('id') ,它返回所需的元素ID
也可以按照以下步骤进行操作:
$('#test').get(0).id等于document.getElementById('test').id
#11楼
id是html Element的属性。 但是,当您编写$("#something") ,它将返回一个jQuery对象,该对象包装了匹配的DOM元素。 要获取第一个匹配的DOM元素,请调用get(0)
$("#test").get(0)
在此本机元素上,您可以调用id或任何其他本机DOM属性或函数。
$("#test").get(0).id
这就是为什么id在您的代码中不起作用的原因。
或者,使用jQuery的attr方法作为其他答案,以获取第一个匹配元素的id属性。
$("#test").attr("id")
#12楼
.id不是有效的jquery函数。 您需要使用.attr()函数来访问元素拥有的属性。 您可以使用.attr()通过指定两个参数来更改属性值,或者通过指定一个来获取值。
http://api.jquery.com/attr/
#13楼
这是一个古老的问题, 但是从2015年开始可能会有效:
$('#test').id;
您还可以进行分配:
$('#test').id = "abc";
只要定义以下JQuery插件:
Object.defineProperty($.fn, 'id', {
get: function () { return this.attr("id"); },
set: function (newValue) { this.attr("id", newValue); }
});
有趣的是,如果element是DOM元素,则:
element.id === $(element).id; // Is true!
#14楼
可能对其他发现此线程的人有用。 以下代码仅在您已经使用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();
#15楼
好吧,似乎还没有解决方案,并且想提出我自己的解决方案,它是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库中的开始。
返回单个字符串值或字符串值数组。 字符串值数组是用于使用多元素选择器的事件。
#16楼
$('#test').attr('id')在您的示例中:
$(document).ready(function() {
alert($('#test').attr('id'));
});
#17楼
由于id是属性,因此可以使用attr方法获取它。
#18楼
// include Database connection file
include("db_connection.php");
// Design initial table header
$data = '
| No. | First Name | Last Name | Email Address | Update | Delete |
|---|---|---|---|---|---|
| '.$number.' | '.$row['first_name'].' | '.$row['last_name'].' | '.$row['email'].' | ||
| Records not found! | |||||
echo $data;
?>
function DeleteUser(id) {
var conf = confirm("Are you sure, do you really want to delete User?");
if (conf == true) {
$.ajax({
url:'deleteUser.php',
method:'POST',
data:{
id:id
},
success:function(data){
alert('delete successfully');
}
}
});
deleteUser.php
// check request
if(isset($_POST['id']) && isset($_POST['id']) != "")
{
// include Database connection file
include("db_connection.php");
// get user id
$user_id = $_POST['id'];
// delete User
$query = "DELETE FROM users WHERE id = '$user_id'";
if (!$result = mysqli_query($con, $query)) {
exit(mysqli_error($con));
}
}
?>
#19楼
它不能回答OP,但可能对其他人很有趣:在这种情况下,您可以访问.id字段:
$('#drop-insert').map((i, o) => o.id)