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

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


当前回答

jQuery方法:

$('#test').attr('id')

在您的示例中:

$(文档).ready(函数){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选择器,并返回结果的array(),而不是其默认功能中的单个元素

jquery中DOM选择器的另一种选择是

$('#test').prop('id')

它不同于.attr()和$('#test').prop('o')获取指定的DOM foo属性,而$('#test').attr“'o'”获取指定的HTML foo属性。

其他回答

这是一个老问题,但截至2015年,这可能会奏效:

$('#test').id;

您还可以分配任务:

$('#test').id = "abc";

只要定义以下JQuery插件:

Object.defineProperty($.fn, 'id', {
    get: function () { return this.attr("id"); },
    set: function (newValue) { this.attr("id", newValue); }
});

有趣的是,如果元素是DOM元素,那么:

element.id === $(element).id; // Is true!

$('#test').attr('id')在您的示例中:

<div id="test"></div>

$(document).ready(function() {
    alert($('#test').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并进行了修改。

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

$('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})