【问题标题】:jQuery .click doesn't work on jQuery-generated buttons [duplicate]jQuery .click 不适用于 jQuery 生成的按钮 [重复]
【发布时间】:2020-09-08 02:47:09
【问题描述】:

我有一个按钮可以生成一个带有文本的 div 和几个带有 jquery 的按钮。

我还有其他完全一样的 div(不是用 jquery 生成的)。

我还有一个事件处理程序 (div_button.click(()=>{//code})),它执行一些任务(更改按钮的颜色并将套接字消息发送到服务器)。

我注意到,当我单击 jQuery 生成的 div 上的按钮时,它不起作用(它仅适用于原始 div)

这是 div 创建者:

socket.on('main', (post) => {
  postContainer.prepend(`
      <div class="py-3 col col-lg-10 mx-auto post" id="${post._id}">
      <div class="toast">
          <div class="toast-header">
              <img src="${post.imgPath}" class="rounded mr-2" height="20" width="20">
              <strong class="mr-auto"><a class="profile-link" href="/user/${post.username}">${post.username}</a></strong>
              <small>${moment(post.time).fromNow()} </small>
          </div>
          <div class="toast-body pb-0">
            ${post.body}
          </div>
          <hr class="mb-0">
          <div>
              <button class="btn btn-link text-muted pr-1 upvote">
                  <svg class="bi bi-shift-fill mb-2 align-baselin" data-rotate="90" width="1em" height="1em" fill="currentColor">
                      <path fill-rule="evenodd" d="M7.27 2.047a1 1 0 011.46 0l6.345 6.77c.6.638.146 1.683-.73 1.683H11.5v3a1 1 0 01-1 1h-5a1 1 0 01-1-1v-3H1.654C.78 10.5.326 9.455.924 8.816L7.27 2.047z" clip-rule="evenodd"/>
                  </svg> 
              </button>
              <span class="mx-1 vote">${post.votes}</span>
              <button class="btn btn-link text-muted pl-1 downvote">
                  <svg class="bi bi-shift-fill rotate align-baseline" width="1em" height="1em" fill="currentColor">
                      <path fill-rule="evenodd" d="M7.27 2.047a1 1 0 011.46 0l6.345 6.77c.6.638.146 1.683-.73 1.683H11.5v3a1 1 0 01-1 1h-5a1 1 0 01-1-1v-3H1.654C.78 10.5.326 9.455.924 8.816L7.27 2.047z" clip-rule="evenodd"/>
                  </svg>
              </button>
          </div>
        </div>
      </div>
    `);
});

这是两个事件监听器之一(都在 "$(() => { //events... })" 内):

  upvote.click(function() {
    let value = Number($(this).next().text())
    let id = $(this).parents(".post").attr("id");
    if ($(this).hasClass('upvoted')) {
    // code
    } else if ($(this).next().hasClass("downvoted")) {
    // code
    } else {
    //code
    }
  });

jQuery 仅适用于非 jQuery 生成的内容,你怎么看?

【问题讨论】:

  • 这是因为在页面加载时按钮的选择器不存在。您需要选择更高级别的元素,然后测试该元素是否具有您创建的按钮的选择器。例如,搜索 .toast .upvoted 之类的内容。

标签: javascript html jquery


【解决方案1】:

代替


$('.yourButtonClass').click(function() {

});

尝试这样的解决方案:


$('body').on('click', '.yourButtonClass', function (e) {

}

这样,.yourButtonClass 的点击事件将始终可用。

【讨论】:

    猜你喜欢
    • 2015-01-25
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 2016-08-22
    • 2017-09-18
    • 2014-06-25
    相关资源
    最近更新 更多