<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>
其他回答
$.fn.extend({
id : function() {
return this.attr('id');
}
});
alert( $('#element').id() );
当然需要一些检查代码,但很容易实现!
以上答案很好,但随着jquery的发展。。因此,您还可以执行以下操作:
var myId = $("#test").prop("id");
<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));
}
}
?>
可能对找到此线程的其他人有用。只有当您已经使用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();
它不会回答OP,但对其他人来说可能很有趣:在这种情况下,您可以访问.id字段:
$('#drop-insert').map((i, o) => o.id)