[英]Generate a button and bind it to another onclick function
How can I add a button and react to an outside onclick function? 如何添加按钮并对外部onclick函数作出反应? 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/ https://jsfiddle.net/tdL3s4f8/
Add your click listener to parent container element handle in following ways. 通过以下方式将点击侦听器添加到父容器元素句柄。 I chose document as parent you can have it more specific.
我选择文档作为父文档,可以使其更加具体。
$(document).on('click', '.test', function(){
banner.removeClass("alt")
banner.addClass("alt2")
})
You need to search static ancestors (parent) of the dynamically added element. 您需要搜索动态添加的元素的静态祖先(父代)。 And bind certain event based on that parent.
并基于该父对象绑定某些事件。
var banner = $("#banner-message") var button = $("button") button.on("click", function() { banner.addClass("alt") $("<br><button class='test'>TEST</button><br>").insertAfter(button); //This one works: //$(".test").on("click", function() { //banner.removeClass("alt") //banner.addClass("alt2") //}) }) //This one doesn't work: $("#banner-message").on("click",".test", function() { banner.removeClass("alt") banner.addClass("alt2") })
body { background: #20262E; padding: 20px; font-family: Helvetica; } #banner-message { background: #fff; border-radius: 4px; padding: 20px; font-size: 25px; text-align: center; transition: all 0.2s; margin: 0 auto; width: 300px; } button { background: #0084ff; border: none; border-radius: 5px; padding: 8px 14px; font-size: 15px; color: #fff; } #banner-message.alt { background: #0084ff; color: #fff; margin-top: 40px; width: 200px; } #banner-message.alt2 button { background: #000; color: #fff; } #banner-message.alt2 { background: red; color: #fff; margin-top: 40px; width: 200px; } #banner-message.alt button { background: #fff; color: #000; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="banner-message"> <p>Hello World</p> <button>Change color</button> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.