首页 > 解决方案 > Generate a button and bind it to another onclick function

问题描述

How can I add a button and react to an outside onclick function? I need it available as well for the generated button and for static buttons that are on the site. At the moment I have the function twice to make it work for both kind of buttons, but that seems kind of redundant.

button.on("click", function() {
  banner.addClass("alt")
  $("<br><button class='test'>TEST</button><br>").insertAfter(button);

  //Here it works for the generated button:
  $(".test").on("click", function() {
    banner.removeClass("alt")
    banner.addClass("alt2")
  })

})

//Here it only works with the static buttons:
$(".test").on("click", function() {
  banner.removeClass("alt")
  banner.addClass("alt2")
})

https://jsfiddle.net/tdL3s4f8/

标签: javascriptjquery

解决方案


通过以下方式将单击侦听器添加到父容器元素句柄。我选择了文档作为父级,你可以让它更具体。

$(document).on('click', '.test', function(){
    banner.removeClass("alt")
    banner.addClass("alt2")
})

推荐阅读