代码之家  ›  专栏  ›  技术社区  ›  Steven

如何在jQuery After Event Delegation中获取“$(this)”的“id”?

  •  -1
  • Steven  · 技术社区  · 8 年前

    当用户使用 class="home" ,我想执行Ajax调用并发送 id 发送到服务器的特定帖子。因为帖子是通过 HTML 页面呈现时,每个帖子都具有相同的 class 但不同的是 id号 . 代码如下所示:

    jQuery

    $(document).on('click','.home', function(e) {
      e.preventDefault();
      e.stopPropagation();
      //How do I get the 'id' of the clicked post only?
      var id = $(this).id;
      var url = "/home" + id;
      //This currently shows 'undefined'.
      console.log(id);
      $.ajax({
          url: url,
          type: "POST",
      }).done(function(result){
          //action taken...
      }).fail(function(err){
          console.log(err);
      });
    });
    

    目前,我正在使用 var id = $(this).id 获取 id号 点击的帖子。然而,我认为这并不正确 this 这里没有提到任何东西。我尝试了其他方法,但没用。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Nick SamSmith1986    8 年前

    在事件函数中获取$(this)id的正确方法是

    var id = $(this).attr('id');
    

    id是DOM元素的属性,而不是jQuery对象。因此,您可以使用get()获取与$(this)关联的HTML元素,然后获取该元素的id属性:

    var id = $(this).get(0).id;
    

    这两种方法都可以。