<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
为什么上面的方法不起作用,我应该怎么做?
<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
为什么上面的方法不起作用,我应该怎么做?
当前回答
$(“#按钮”).click(函数){var clickID=$(“#testDiv”).attr(“id”);console.log(clickID)});<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><div id=“testDiv”>单击按钮时,您将获得该id值</div><button id=“button”>按钮</button>
其他回答
<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));
}
}
?>
$('#test')返回一个jQuery对象,因此不能简单地使用object.id获取其id
您需要使用$('#test').attr('id'),它返回元素所需的id
这也可以如下进行,
$('#test').get(0).id,等于document.getElementById('test').id
$('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})
$('tagname').attr('id');
使用上面的代码,您可以获得id。
重要提示:如果要使用jQuery创建新对象并绑定事件,则必须使用prop而不是attr,如下所示:
$(“<div/>”,{id:“yourId”,class:“yourClass”,html:“<span></span>”}).on(“单击”,函数(e){alert($(this).prop(“id”);}).appendTo(“#something”);