<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
为什么上面的方法不起作用,我应该怎么做?
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').get(0)
,甚至是$('#test')[0]
的原因是$('#test')
是JQuery的选择器,**返回一个数组()的结果,而不是其默认功能中的一个元素
Jquery中DOM选择器的一个替代方法是
$('#test').prop('id')
这与.attr()
不同,$('#test').prop('foo')
抓取指定的DOMfoo
属性,而$('#test').attr('foo')
抓取指定的HTMLfoo
属性,你可以找到更多关于差异的细节这里 。
id
是htmlElement
的一个属性。
然而,当你写"$("#something") "时,它会返回一个jQuery对象来封装匹配的DOM元素。
要得到第一个匹配的DOM元素,调用get(0)
。
$("#test").get(0)
在这个原生元素上,你可以调用id,或者其他任何原生DOM属性或函数。
$("#test").get(0).id
这就是为什么id
在你的代码中不起作用的原因。
或者,使用jQuery的attr
方法,就像其他答案所建议的那样,获取第一个匹配元素的id
属性。
$("#test").attr("id")
好吧,似乎还没有一个解决方案,我想提出我自己的解决方案,这是一个扩展的JQuery原型'的。
我把它放在一个Helper文件中,在JQuery库后加载,因此检查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的情况下才会有效。 该函数总是返回一个标识符,如果元素没有标识符,该函数就会生成标识符并将其追加到元素中。 如果元素没有标识符,函数会生成标识符,并将其附加到元素中。
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();
这是一个老问题了,但从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!
这可以是元素的id,类,甚至自动使用
------------------------
$(this).attr('id');
=========================
------------------------
$("a.remove[data-id='2']").attr('id');
=========================
------------------------
$("#abc1'").attr('id');
=========================
由于id是一个属性,所以你可以通过attr
方法获得。
这将最终解决你的问题。
假设你在一个页面上有很多按钮,你想根据他们的ID用jQuery Ajax改变其中的一个按钮(或者不是ajax)。
也可以说,你有许多不同类型的按钮(用于表单,用于审批和类似的目的),你想让jQuery只处理"like" 按钮,而你希望jQuery只处理"like"按钮。
这里有一段工作代码。 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,并进行了修改。
<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));
}
}
?>