javascript - add event to element after it remove itself and append itself again
问题描述
I tried to remove a button and alert() when i click it, then the function will append a 'same' button to a container div, after searching senior's legacy, i tried to use on()/live()/delegate()/ unfortunately they not work.
<body>
<div id="container"></div>
<hr>
<button onclick="clicked()">Other one</button>
<hr>
</body>
<script>
$(document).ready(function(){
var i = 0;
$("#container").append("<button id='btn_sub' onclick='clicked()'>Click Me!</button>");
$("[id='btn_sub']").delegate(this,"click",function(){
$("#container").empty();
$("#container").append("<button id='btn_sub' onclick='clicked()'>Click Me!"+i+"</button>");
i++;
});//tried click/on click/live
});
function clicked(){
alert(1);
}
</script>
Finally, in this example, the clicked function put out of $(document).ready() and the part of alert worked.
Is there any other method to do the same effect? and why on()/live()/delegate()/ not work?
Thanks.
解决方案
First off $("[id='btn_sub']")
can be replaced with $("#btn_sub")
, then it's actually better to use a class as you might have many buttons.
This is a working example as an illustration: https://codepen.io/antoniandre/pen/XoNNpO
$(document).ready(function(){
$("#container").on("click", '.btn_sub', function() {
removeButton(this);
});
});
function addButton() {
$("#container").append("<button class='btn_sub'>Delete Me!</button>");
}
function removeButton(btn) {
btn.remove();
}
With the
on()
bound on the container, you actually make sure any matching button.btn_sub
will get this event attached to them when they are created in the future.Regarding
live
, it does the same ason
but is now deprecated so you can forget it. https://api.jquery.com/live/#live-events-handler
推荐阅读
- html - 如何在 div 元素上显示边框 css?
- arrays - 二维阵列螺旋算法中的逻辑错误
- go - 管理通过非标准端口访问的自定义 Go 模块
- android - 带有 onClicklistener 的 ViewHolder 带有 UninitializedPropertyAccessException 的问题
- python-3.x - 使用 Beautifuloup 在一行内查找带有标签搜索的字符串
- python - 条形图和折线图上 mathplotlib 中 x 轴的不正确对齐
- r - 如何将我的数据和问题放入 Rstudio 中 ape pakage 的 ace 函数的脚本中?
- python - Python(硒):如何在现有的html代码中搜索新的html文档
- qbs - 确定先前构建使用的属性
- node.js - 在 Node JS 和 Sequelize 中查询 N:M 关联的连接表