如何使用 jQuery 获取元素的 ID?

发布于 2024-09-08 23:36:45 字数 185 浏览 4 评论 0原文

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

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

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

Why doesn't the above work, and how should I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

甜警司 2024-09-15 23:36:45

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>

或者通过 DOM:

$('#test').get(0).id;

甚至 :

$('#test')[0].id;

以及在 JQuery 中使用 $('#test').get(0) 甚至 $('#test')[0]< 的原因/code> 是 $('#test') 是一个 JQuery 选择器,并且返回结果的 array(),其默认功能不是单个元素,而是

DOM 的替代方案jquery 中的选择器

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

.attr() 不同,$('#test').prop('foo') 抓取指定的 DOM foo< /code> 属性,而 $('#test').attr('foo') 获取指定的 HTML foo 属性,您可以找到有关差异的更多详细信息此处

The jQuery way:

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

In your example:

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

Or through the DOM:

$('#test').get(0).id;

or even :

$('#test')[0].id;

and reason behind usage of $('#test').get(0) in JQuery or even $('#test')[0] is that $('#test') is a JQuery selector and returns an array() of results not a single element by its default functionality

an alternative for DOM selector in jquery is

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

which is different from .attr() and $('#test').prop('foo') grabs the specified DOM foo property, while $('#test').attr('foo') grabs the specified HTML foo attribute and you can find more details about differences here.

只涨不跌 2024-09-15 23:36:45

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

如果您的匹配集包含多个元素,您可以使用传统的 .each 迭代器< /a> 返回一个包含每个 id 的数组:

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

或者,如果您愿意变得更加坚韧,您可以避免使用包装器并使用 .map 快捷方式

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

$('selector').attr('id') will return the id of the first matched element. Reference.

If your matched set contains more than one element, you can use the conventional .each iterator to return an array containing each of the ids:

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

Or, if you're willing to get a little grittier, you can avoid the wrapper and use the .map shortcut.

return $('.selector').map(function(index,dom){return dom.id})
烧了回忆取暖 2024-09-15 23:36:45

id 是 html Element 的属性。但是,当您编写 $("#something") 时,它会返回一个包装匹配 DOM 元素的 jQuery 对象。要获取第一个匹配的 DOM 元素,请调用 get(0)

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

在此本机元素上,您可以调用 id 或任何其他本机 DOM 属性或函数。

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

这就是 id 在您的代码中不起作用的原因。

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

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

id is a property of an html Element. However, when you write $("#something"), it returns a jQuery object that wraps the matching DOM element(s). To get the first matching DOM element back, call get(0)

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

On this native element, you can call id, or any other native DOM property or function.

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

That's the reason why id isn't working in your code.

Alternatively, use jQuery's attr method as other answers suggest to get the id attribute of the first matching element.

$("#test").attr("id")
酷炫老祖宗 2024-09-15 23:36:45

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

var myId = $("#test").prop("id");

Above answers are great, but as jquery evolves.. so you can also do:

var myId = $("#test").prop("id");
忘羡 2024-09-15 23:36:45
$.fn.extend({
    id : function() {
        return this.attr('id');
    }
});

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

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

$.fn.extend({
    id : function() {
        return this.attr('id');
    }
});

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

Some checking code required of course, but easily implemented!

花伊自在美 2024-09-15 23:36:45

如果您想获取某个元素的 ID(假设通过类选择器),当在该特定元素上触发事件(在本例中为单击事件)时,则以下代码将完成这项工作:

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

If you want to get an ID of an element, let's say by a class selector, when an event (in this case click event) was fired on that specific element, then the following will do the job:

 $('.your-selector').click(function(){
       var id = $(this).attr('id');
 });
小傻瓜 2024-09-15 23:36:45

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

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

.id is not a valid jquery function. You need to use the .attr() function to access attributes an element possesses. You can use .attr() to both change an attribute value by specifying two parameters, or get the value by specifying one.

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

静若繁花 2024-09-15 23:36:45

$('#test').attr('id')
在你的例子中:

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

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

$('#test').attr('id')
In your example:

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

$(document).ready(function() {
    alert($('#test').attr('id'));
}); 
街角卖回忆 2024-09-15 23:36:45
    $("#button").click(function() {
      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"> When button will click you'll get this id value </div>
<button id="button"> Button </button>

    $("#button").click(function() {
      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"> When button will click you'll get this id value </div>
<button id="button"> Button </button>

慕烟庭风 2024-09-15 23:36:45

好吧,似乎还没有解决方案,我想提出我自己的解决方案,即 JQuery 原型的扩展。我将其放入在 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 库中的一个开始。

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

Well, seems there has not been a solution and would like to propose my own solution that is an expansion of the JQuery prototype's. I put this in a Helper file that is loaded after the JQuery library, hence the check for 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');
        }
    }
}

It may not be perfect but it is a start to maybe getting inclusion into the JQuery library.

Returns either a single string value or an Array of string values. The Array of string values, is for the event an multi-element selector was used.

隐诗 2024-09-15 23:36:45

$('#test') 返回一个 jQuery 对象,因此您不能简单地使用 object.id 来获取

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

这也可以按如下方式完成,

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

$('#test') returns a jQuery object, so you can't use simply object.id to get its Id

you need to use $('#test').attr('id'), which returns your required ID of the element

This can also be done as follows ,

$('#test').get(0).id which is equal to document.getElementById('test').id

楠木可依 2024-09-15 23:36:45
$('tagname').attr('id');

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

$('tagname').attr('id');

Using above code you can get id.

长梦不多时 2024-09-15 23:36:45

也许对找到此线程的其他人有用。仅当您已经使用 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();

Maybe useful for others that find this thread. The code below will only work if you already use jQuery. The function returns always an identifier. If the element doesn't have an identifier the function generates the identifier and append this to the element.

var generatedIdCounter = 0;

$.fn.id = function() {
    var identifier = this.attr('id');

    if(!identifier) {
        generatedIdCounter++;
        identifier = 'isGenerated_' + generatedIdCounter;

        this.attr('id', identifier);
    }

    return identifier;
}

How to use:

$('.classname').id();

$('#elementId').id();
我的痛♀有谁懂 2024-09-15 23:36:45

这是一个老问题,但是从 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!

This is an old question, but as of 2015 this may actually work:

$('#test').id;

And you can also make assignments:

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

As long as you define the following JQuery plugin:

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

Interestingly, if element is a DOM element, then:

element.id === $(element).id; // Is true!
被翻牌 2024-09-15 23:36:45

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

Since the id is an attribute, you can get it by using the attr method.

金橙橙 2024-09-15 23:36:45

这可以是元素 id 、 class ,或者自动使用 Even

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

This can be element id , class , or automatically using even

------------------------
$(this).attr('id');
=========================
------------------------
$("a.remove[data-id='2']").attr('id');
=========================
------------------------
$("#abc1'").attr('id');
=========================
梦途 2024-09-15 23:36:45

这将最终解决您的问题:

假设您在页面上有许多按钮,并且您想根据按钮的 ID 使用 jQuery Ajax(或不使用 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 并进行了更改。

This will finally solve your problems:

lets say you have many buttons on a page and you want to change one of them with jQuery Ajax (or not ajax) depending on their ID.

lets also say that you have many different type of buttons (for forms, for approval and for like purposes), and you want the jQuery to treat only the "like" buttons.

here is a code that is working:
the jQuery will treat only the buttons that are of class .cls-hlpb,
it will take the id of the button that was clicked
and will change it according to the data that comes from the 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>

code was taken from w3schools and changed.

眼趣 2024-09-15 23:36:45
<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));
    }
}
?>
<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));
    }
}
?>
盗心人 2024-09-15 23:36:45

它不回答OP,但其他人可能会感兴趣:在这种情况下您可以访问 .id 字段:

$('#drop-insert').map((i, o) => o.id)

it does not answer the OP, but may be interesting to others: you can access the .id field in this case:

$('#drop-insert').map((i, o) => o.id)
不乱于心 2024-09-15 23:36:45

重要提示:如果您使用 jQuery 创建新对象并绑定事件,则必须使用 prop 而不是 attr,如下所示:

$("

",{ id: "yourId", class: "yourClass", html: "" }).on("click", function(e ) {alert($(this).prop("id")); }).appendTo("#something");

Important: if you are creating a new object with jQuery and binding an event, you MUST use prop and not attr, like this:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文