当前位置:   article > 正文

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

hlpbtn
  1. <div id="test"></div>
  2. <script>
  3. $(document).ready(function() {
  4. alert($('#test').id);
  5. });
  6. </script>

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


#1楼

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

使用上面的代码,您可以获得ID。


#2楼

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

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

#3楼

  1. $.fn.extend({
  2. id : function() {
  3. return this.attr('id');
  4. }
  5. });
  6. alert( $('#element').id() );

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


#4楼

如果要获取某个元素的ID,则由类选择器说,当在该特定元素上触发一个事件(在本例中为click事件)时,将执行以下操作:

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

#5楼

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

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


#6楼

这可以是元素id,class,也可以自动使用甚至

  1. ------------------------
  2. $(this).attr('id');
  3. =========================
  4. ------------------------
  5. $("a.remove[data-id='2']").attr('id');
  6. =========================
  7. ------------------------
  8. $("#abc1'").attr('id');
  9. =========================

#7楼

这最终将解决您的问题:

假设您在页面上有许多按钮,并且您想根据其ID使用jQuery Ajax(或不使用ajax)更改其中一个按钮。

还可以说您有许多不同类型的按钮(用于表单,用于批准和用于类似目的),并且您希望jQuery只处理“喜欢”按钮。

这是一个有效的代码:jQuery将仅处理.cls-hlpb类的按钮,它将获取被单击的按钮的ID,并将根据来自Ajax的数据对其进行更改。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
  5. <script>
  6. $(document).ready(function(){
  7. $(".clshlpbtn").on('click',function(e){
  8. var id = $(e.target).attr('id');
  9. alert("The id of the button that was clicked: "+id);
  10. $.post("demo_test_post.asp",
  11. {
  12. name: "Donald Duck",
  13. city: "Duckburg"
  14. },
  15. function(data,status){
  16. //parsing the data should come here:
  17. //var obj = jQuery.parseJSON(data);
  18. //$("#"+id).val(obj.name);
  19. //etc.
  20. if (id=="btnhlp-1")
  21. $("#"+id).attr("style","color:red");
  22. $("#"+id).val(data);
  23. });
  24. });
  25. });
  26. </script>
  27. </head>
  28. <body>
  29. <input type="button" class="clshlpbtn" id="btnhlp-1" value="first btn"> </input>
  30. <br />
  31. <input type="button" class="clshlpbtn" id="btnhlp-2" value="second btn"> </input>
  32. <br />
  33. <input type="button" class="clshlpbtn" id="btnhlp-9" value="ninth btn"> </input>
  34. </body>
  35. </html>

代码取自w3schools,并已更改。


#8楼

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')[0]使用$('#test').get(0)$('#test')是一个JQuery选择器并返回array()结果的功能不是单个元素

jQuery中DOM选择器的替代方法是

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

这与.attr()$('#test').prop('foo') ,它获取指定的DOM foo属性,而$('#test').attr('foo')获取指定的HTML foo属性,您可以在此处找到有关差异的更多详细信息。


#9楼

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

如果匹配的集合包含多个元素,则可以使用常规的.each 迭代器返回包含每个id的数组:

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

或者,如果您愿意加一点勇气,可以避免使用包装器,而可以使用.map 快捷方式

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

#10楼

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

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

也可以按照以下步骤进行操作:

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


#11楼

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

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

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

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

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

或者,使用jQuery的attr方法作为其他答案,以获取第一个匹配元素的id属性。

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

#12楼

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

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


#13楼

这是一个古老的问题, 但是从2015年开始可能会有效:

$('#test').id;

您还可以进行分配:

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

只要定义以下JQuery插件:

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

有趣的是,如果element是DOM元素,则:

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

#14楼

可能对其他发现此线程的人有用。 以下代码仅在您已经使用jQuery的情况下有效。 该函数始终返回一个标识符。 如果该元素没有标识符,则函数会生成该标识符并将其附加到该元素。

  1. var generatedIdCounter = 0;
  2. $.fn.id = function() {
  3. var identifier = this.attr('id');
  4. if(!identifier) {
  5. generatedIdCounter++;
  6. identifier = 'isGenerated_' + generatedIdCounter;
  7. this.attr('id', identifier);
  8. }
  9. return identifier;
  10. }

如何使用:

  1. $('.classname').id();
  2. $('#elementId').id();

#15楼

好吧,似乎还没有解决方案,并且想提出我自己的解决方案,它是JQuery原型的扩展。 我将其放在JQuery库之后加载的Helper文件中,因此检查window.jQuery

  1. if (window.jQuery) {
  2. $.prototype.id = function () {
  3. if (this.length > 1) {
  4. var val = [];
  5. this.each(function (idx, el) {
  6. val.push($(el).id());
  7. });
  8. return val;
  9. } else {
  10. return this.attr('id');
  11. }
  12. }
  13. }

它可能并不完美,但是它可能成为包含在JQuery库中的开始。

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


#16楼

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

  1. <div id="test"></div>
  2. $(document).ready(function() {
  3. alert($('#test').attr('id'));
  4. });

#17楼

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


#18楼

  1. <html>
  2. <head>
  3. <link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  5. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  6. </head>
  7. <?php
  8. // include Database connection file
  9. include("db_connection.php");
  10. // Design initial table header
  11. $data = '<table class="table table-bordered table-striped">
  12. <tr>
  13. <th>No.</th>
  14. <th>First Name</th>
  15. <th>Last Name</th>
  16. <th>Email Address</th>
  17. <th>Update</th>
  18. <th>Delete</th>
  19. </tr>';
  20. $query = "SELECT * FROM users";
  21. if (!$result = mysqli_query($con, $query)) {
  22. exit(mysqli_error($con));
  23. }
  24. // if query results contains rows then featch those rows
  25. if(mysqli_num_rows($result) > 0)
  26. {
  27. $number = 1;
  28. while($row = mysqli_fetch_assoc($result))
  29. {
  30. $data .= '<tr>
  31. <td>'.$number.'</td>
  32. <td>'.$row['first_name'].'</td>
  33. <td>'.$row['last_name'].'</td>
  34. <td>'.$row['email'].'</td>
  35. <td><button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button>
  36. </td>
  37. </tr>';
  38. $number++;
  39. }
  40. }
  41. else
  42. {
  43. // records now found
  44. $data .= '<tr><td colspan="6">Records not found!</td></tr>';
  45. }
  46. $data .= '</table>';
  47. echo $data;
  48. ?>
  49. <script type="text/javascript">
  50. function DeleteUser(id) {
  51. var conf = confirm("Are you sure, do you really want to delete User?");
  52. if (conf == true) {
  53. $.ajax({
  54. url:'deleteUser.php',
  55. method:'POST',
  56. data:{
  57. id:id
  58. },
  59. success:function(data){
  60. alert('delete successfully');
  61. }
  62. }
  63. });
  64. deleteUser.php
  65. <?php
  66. // check request
  67. if(isset($_POST['id']) && isset($_POST['id']) != "")
  68. {
  69. // include Database connection file
  70. include("db_connection.php");
  71. // get user id
  72. $user_id = $_POST['id'];
  73. // delete User
  74. $query = "DELETE FROM users WHERE id = '$user_id'";
  75. if (!$result = mysqli_query($con, $query)) {
  76. exit(mysqli_error($con));
  77. }
  78. }
  79. ?>

#19楼

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

$('#drop-insert').map((i, o) => o.id)
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/574197
推荐阅读
相关标签
  

闽ICP备14008679号