<div id="test"></div>
<script>
  $(document).ready(function() {
    alert($('#test').id);
  });  
</script>

为什么上面的方法不起作用,我应该怎么做?


当前回答

如果您想获取一个元素的ID,比如说通过类选择器,当在该特定元素上触发事件(在本例中为单击事件)时,以下操作将完成此任务:

 $('.your-selector').click(function(){
       var id = $(this).attr('id');
 });

其他回答

这将最终解决您的问题:

假设您在一个页面上有多个按钮,您希望根据其ID使用jQueryAjax(或不是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并进行了修改。

由于id是一个属性,您可以使用attr方法获取它。

<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));
    }
}
?>

$(“#按钮”).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>

.id不是有效的jquery函数。您需要使用.attr()函数来访问元素拥有的属性。您可以使用.attr()通过指定两个参数来更改属性值,或者通过指定一个参数来获取值。

http://api.jquery.com/attr/