如何使用jquery迭代具有相同属性的html元素并查找onclick事件

How to iterate over html elements with same attribute using jquery and look for onclick event?

本文关键字:元素 html 查找 事件 onclick 属性 jquery 何使用 迭代      更新时间:2023-09-26

我试图循环遍历具有相同属性的每个元素,并在任何元素中出现onclick事件时进行ajax调用。

 $(document).ready(function(){
    $.each($("#workon"),function(){
       $(this).find("#wanalearn_request").click(function(e){
          e.preventDefault();
          var this_ = this;
          # ajaxPost is just a custom ajax post function 
          ajaxPost($(this).attr('href'),{},function(content) {
             $(this_).find('span').text(content.wanalearns_count);
          });
       });
   });
});

尝试使用"on"代替:

$('#workon').on('click', '#wanalearn_request', function (e) {
  e.preventDefault();
  e.stopPropagation();
  var link = $(e.target).closest('a');
  $.post(link.attr('href'), '' /* the payload must be a serialized query string in this case */, function (content) {
    link.find('span').text(content.wanalearns_count);
  });
});