<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
为什么上述方法不起作用,我应该怎么做?
#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 ,如下所示:
$("<div/>",{ id: "yourId", class: "yourClass", html: "<span></span>" }).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的数据对其进行更改。
<!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,并已更改。
#8楼
jQuery方式:
$('#test').attr('id')
在您的示例中:
$(document).ready(function() { 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')[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()
通过指定两个参数来更改属性值,或者通过指定一个来获取值。
#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')
在您的示例中:
<div id="test"></div>
$(document).ready(function() {
alert($('#test').attr('id'));
});
#17楼
由于id是属性,因此可以使用attr
方法获取它。
#18楼
<html>
<head>
<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<?php
// include Database connection file
include("db_connection.php");
// Design initial table header
$data = '<table class="table table-bordered table-striped">
<tr>
<th>No.</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>Update</th>
<th>Delete</th>
</tr>';
$query = "SELECT * FROM users";
if (!$result = mysqli_query($con, $query)) {
exit(mysqli_error($con));
}
// if query results contains rows then featch those rows
if(mysqli_num_rows($result) > 0)
{
$number = 1;
while($row = mysqli_fetch_assoc($result))
{
$data .= '<tr>
<td>'.$number.'</td>
<td>'.$row['first_name'].'</td>
<td>'.$row['last_name'].'</td>
<td>'.$row['email'].'</td>
<td><button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button>
</td>
</tr>';
$number++;
}
}
else
{
// records now found
$data .= '<tr><td colspan="6">Records not found!</td></tr>';
}
$data .= '</table>';
echo $data;
?>
<script type="text/javascript">
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
<?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)