简体   繁体   English

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

[英]How to get the id of the attribute from an element using jquery?

i wrote this mini jquery snippet, but i want to get the id of the li element so i can post this data to an ajax call this is my script 我写了这个迷你jquery片段,但我想获取li元素的ID,以便我可以将此数据发布到ajax中,这是我的脚本

 $('#list li a').on('click', function(e) {

        var id = ? //need to get li id
        e.preventDefault();

        $.ajax({
        type: "POST",
        url: "unfollow.php",
        data: id,
        success: function(){
            $(this).parent().hide();
        $('.updateNumber').html(function(){
            return parseInt($(this).text(),10)+1;
          });
        }
         });
       });
    });

this is an example html list: 这是一个示例html列表:

<ul id="list">
    <li id="list_1" class="list"><a href="">hide</a></li>
</ul>

thanks :) 谢谢 :)

 $('#list li a').on('click', function(e) {
    var id = $(this).parent("li").attr("id");
    e.preventDefault();

    $.ajax({
    type: "POST",
    url: "unfollow.php",
    data: id,
    success: function(){
        $(this).parent().hide();
    $('.updateNumber').html(function(){
        return parseInt($(this).text(),10)+1;
      });
    }
     });
   });
});

You could use plain javascript (no need for the extra calls to jQuery) 您可以使用普通的javascript(不需要对jQuery的额外调用)

var id = this.parentNode.id 

fiddle here http://jsfiddle.net/rL29r/ 在这里摆弄http://jsfiddle.net/rL29r/

EDIT - to get just the number 编辑-仅获取数字

var id = this.parentNode.id.replace('list_', '')

http://jsfiddle.net/rL29r/2/ http://jsfiddle.net/rL29r/2/

由于您要匹配的<a>元素是<li>元素的后代,并且您似乎想要祖先<li>元素的id ,因此可以使用close()方法:

var id = $(this).closest("li").attr("id");
id = this.parentNode.id;

This is at least 8 times faster than the jQuery equivalent. 这至少比jQuery快8倍。 Don't use jQuery for something so simple. 不要将jQuery用于如此简单的事情。

Check this demo on jsFiddle.net. 在jsFiddle.net上查看此演示 You will need to use .parent() with $(this) . 您将需要将.parent()$(this)

HTML 的HTML

<ul id="list">
  <li id="list_1">
    <a href="#">Test Anchor One</a>
  </li>
  <li id="list_2">
    <a  href="#">Test Anchor Two</a>
  </li>
</ul>​

JavaScript 的JavaScript

$('#list li a').on('click', function(e) {
    var id = $(this).parent().attr("id").replace("list_", "");
   alert(id);
});​

This will give 1 or 2 as id . 这将给12作为id Hope this helps you. 希望这对您有所帮助。

For the number of list_n use 对于list_n使用

var id = this.parentNode.id;
var number = id.substring(5);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM