如何获得' id' ' $(this)'在jQuery After Event Delegation?

时间:2018-03-17 02:18:31

标签: javascript jquery

当用户点击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 个答案:

答案 0 :(得分:0)

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

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

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

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

其中任何一个都可以。