Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何获得';id';属于'$(本)及"x27 ;;在jQuery中,事件后委派?_Javascript_Jquery - Fatal编程技术网

Javascript 如何获得';id';属于'$(本)及"x27 ;;在jQuery中,事件后委派?

Javascript 如何获得';id';属于'$(本)及"x27 ;;在jQuery中,事件后委派?,javascript,jquery,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 on

当用户使用
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);
  });
});

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

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

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

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

这两种方法都可以使用。

您尝试了
$(文档)。在('submit'、'.post',function(){})
?我刚刚发现这很好,是
id
不起作用。很抱歉。只是想知道,在('submit'、'.post',function(){})上,
$(document).之后,您如何获得已提交的
.post
id
?用HTML代码示例编辑您的问题。在您的函数中,您可以尝试var id=$(this).id;当我
console.log(id)
时,它会显示
undefined