如何用jQuery获得一个元素的ID?

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

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

对该问题的评论 (1)
解决办法

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>
评论(20)

$('selector').attr('id')将返回第一个匹配元素的id。参考.

如果你的匹配集合包含多个元素,你可以使用传统的.eachiterator来返回一个包含每个id的数组。

var retval = []
$('selector').each(function(){
  retval.push($(this).attr('id'))
})
return retval

或者,如果你愿意变得更狡猾一些,你可以避免使用包装器,而使用.map快捷方式

return $('.selector').map(function(index,dom){return dom.id})
评论(3)

id是htmlElement的一个属性。 然而,当你写"$("#something") "时,它会返回一个jQuery对象来封装匹配的DOM元素。 要得到第一个匹配的DOM元素,调用get(0)

$("#test").get(0)

在这个原生元素上,你可以调用id,或者其他任何原生DOM属性或函数。

$("#test").get(0).id

这就是为什么id在你的代码中不起作用的原因。

或者,使用jQuery的attr方法,就像其他答案所建议的那样,获取第一个匹配元素的id属性。

$("#test").attr("id")
评论(0)

上面的答案很好,但是随着jquery的发展......。 你也可以这样做。

var myId = $("#test").prop("id");
评论(3)
$.fn.extend({
    id : function() {
        return this.attr('id');
    }
});

alert( $('#element').id() );

当然需要一些检查代码,但很容易实现!

评论(1)

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

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

评论(0)

如果你想获得一个元素的ID,比如说通过类选择器,当一个事件(在这种情况下是点击事件)在这个特定的元素上被触发时,那么下面的代码就可以完成这个工作。

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

好吧,似乎还没有一个解决方案,我想提出我自己的解决方案,这是一个扩展的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库中。

返回单个字符串值或字符串值的数组。 字符串值的数组,是用于多元素选择器的事件。

评论(0)

$('#test')返回一个jQuery对象,所以你不能简单地使用object.id来获得其Id

你需要使用$('#test').attr('id'),它返回你所需要的元素的`ID'。

这也可以通过以下方式实现。

$('#test').get(0).id,等于document.getElementById('test').id

评论(1)

$(&#39;#test&#39;).attr(&#39;id&#39;) 在您的例子中。

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

$(document).ready(function() {
    alert($('#test').attr('id'));
}); 
评论(0)

也许对其他找到这个帖子的人有用。 下面的代码只有在你已经使用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();
评论(0)
$('tagname').attr('id');

使用上面的代码可以得到id。

评论(0)

这是一个老问题了,但从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!
评论(0)

这可以是元素的id,类,甚至自动使用

------------------------
$(this).attr('id');
=========================
------------------------
$("a.remove[data-id='2']").attr('id');
=========================
------------------------
$("#abc1'").attr('id');
=========================
评论(0)

由于id是一个属性,所以你可以通过attr方法获得。

评论(0)

它没有回答OP,但可能对其他人感兴趣。 在这种情况下,你可以访问.id字段。

$(&#39;#drop-insert&#39;).map((i, o) =>
o.id)
评论(1)

重要的是。 如果你用jQuery创建一个新的对象并绑定一个事件,你必须*使用prop而不是attr*,就像这样。

$("<div/>",{ id: "yourId", class: "yourClass", html: "<span></span>&quot。 }).on("click", function(e) { alert($(this).prop("id")); }).appendTo("#something");

评论(0)

这将最终解决你的问题。

假设你在一个页面上有很多按钮,你想根据他们的ID用jQuery Ajax改变其中的一个按钮(或者不是ajax)。

也可以说,你有许多不同类型的按钮(用于表单,用于审批和类似的目的),你想让jQuery只处理"like" 按钮,而你希望jQuery只处理"like"按钮。

这里有一段工作代码。 jQuery将只处理类.cls-hlpb的按钮。 它将采用被点击的按钮的ID。 并会根据ajax传来的数据进行修改。





<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>



<input type="button" class="clshlpbtn" id="btnhlp-1" value="first btn">            
评论(0)



  <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>

<?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>Delete
                </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));
    }
}
?>
评论(0)