Javascript jQuery.click不';不能使用jQuery生成的按钮

Javascript jQuery.click不';不能使用jQuery生成的按钮,javascript,html,jquery,Javascript,Html,Jquery,我有一个按钮可以生成一个包含文本的div,还有几个按钮可以生成jquery 我还有其他类似的div(不是用jquerytho生成的) 我还有一个事件处理程序(div_button.click(()=>{//code})),它执行一些任务(更改按钮的颜色并向服务器发送套接字消息) 我注意到,当我单击jQuery生成的div上的按钮时,它不起作用(它只在原始div中起作用) 这是div创建者: socket.on('main', (post) => { postContainer.prep

我有一个按钮可以生成一个包含文本的div,还有几个按钮可以生成jquery

我还有其他类似的div(不是用jquerytho生成的)

我还有一个事件处理程序(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>
    `);
});
jQuery只对非jQuery生成的内容有效,您认为如何?

而不是


$('.yourButtonClass')。单击(函数(){
});
尝试以下解决方案:


$('body')。在('click','yourButtonClass',函数(e){
}

这样,单击事件将始终适用于
。yourButtonClass

,这是因为加载页面时按钮的选择器不存在。您需要选择更高级别的元素,然后测试该元素是否具有您创建的按钮选择器。例如,搜索类似
.toast的内容。向上投票
  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
    }
  });