javascript - 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")
})
解决方案
通过以下方式将单击侦听器添加到父容器元素句柄。我选择了文档作为父级,你可以让它更具体。
$(document).on('click', '.test', function(){
banner.removeClass("alt")
banner.addClass("alt2")
})
推荐阅读
- spring - 服务激活器映射到 kafka 成功通道作为输入通道,但无法在 kafka 上执行发送成功
- java - Java 程序在 IDE 上运行,但不在终端上
- kubernetes - 在 Kubernetes 中手动将作业的状态更改为成功
- java - Spring Project 未在 Eclipse 中构建
- firebase - 有没有办法将 Firestore 安全规则应用于管理 SDK?
- r - 如何从 R Shiny App 中的其他反应输出创建反应输出?
- javascript - JQuery - 将随机数添加到数组中,然后在打印数组之前检查是否有重复
- dotnetnuke - 升级到 DNN 9.6.4 后,2sxc 工具栏不可见
- sql - 甲骨文 SQL | 提供 id 时,自动递增的 ID 不会递增
- django - Django Page Not Found / No Post 匹配给定的查询