最近我发布了一个question ,询问为什么我的一些 javascript 代码行为不当。然而,接受的答案并没有完全解决我的问题,所以我再次来到这里。
问题描述
- 我有一个
<div>
其中有一组单选按钮。 - 我使用 jquery ui 来设置该集合的样式
buttonset()
。它看起来相当漂亮。 - 然后我清空
<div>
使用 jquery 做一些事情来达到$("#mydiv").html("")
的效果 - 然后我再次恢复已删除的准确内容。
- 最后,按钮集不再正常工作,因为它的事件在此过程中发生了困惑。
所以我的问题是当我临时修改 DOM 时,如何保护此类绑定(bind)事件不被垃圾收集?
注意!我做不到display:none
隐藏<div>
相反,因为删除 html 内容并稍后恢复它的整个业务是由一个未命名的 jquery 插件处理的。我也无法调用buttonset()
再次,因为a)图形样式变得困惑,b)在我的实际问题中还有其他控件没有这种方便的功能。因此,我真正需要的是某种方法来保护所有这些处理程序,而它们应该控制的行为的元素暂时从 DOM 中丢失。
示例代码
HTML
<div id="container">
<div id="buttonset">
<input type="radio" id="radio1" name="option" />
<label for="radio1">X</label>
<input type="radio" id="radio2" name="option" />
<label for="radio2">Y</label>
<input type="radio" id="radio3" name="option" />
<label for="radio3">Z</label>
</div>
</div>
<div id="control">
<input id="toggle" type="checkbox"/>
<label for="toggle">Toggle</label>
</div>
Javascript
$(function(){
$("#buttonset").buttonset();
$("#toggle").click(
function(){
if($(this).is(":checked"))
{
backup = $("#container").html();
$("#container").html("");
} else $("#container").html(backup);
}
)
});
可玩版本
解决方案
我在应用 buttonset()
之前使用了已接受答案中的想法来保存 html 内容,然后重新申请buttonset()
每次根据需要使用已保存的数据。
最佳答案
更新:
这是更新的 fiddle这和你的OP非常接近。基本思想是销毁
buttonset
以恢复原始html
$(function() {
//Turn the radio buttons into a jquery ui buttonset
$("#buttonset").buttonset();
//Use the toggle button to hide/show the #container div.
//NB! It's not possible to do css display:none instead,
//due to some other limitations, to wit, I'm using a
//library that I can not modify.
$("#toggle").button();
var backup; // added this to prevent it from leaking onto global scope.
$("#toggle").click(function() {
if ($(this).is(":checked")) {
// restore the html back
$("#buttonset").buttonset("destroy");
backup = $("#container").html();
$("#container").html("");
}
else {
$("#container").html(backup);
$("#buttonset").buttonset();
}
})
});
关于javascript - 保护未指定的 Javascript 事件处理程序不被垃圾收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7032323/