最近,我摆了一个question,询问为什么我的某些JavaScript代码行为异常。但是,被接受的答案并不能完全解决我的问题,因此我再次回到这里。

问题描述


我有一个<div>,其中有一个单选按钮集合。
我使用jquery ui用buttonset()设置该集合的样式。看起来很漂亮。
然后我通过对<div>的效果做一些事用jQuery清空$("#mydiv").html("")
然后,我再次恢复已删除的确切内容。
最终,按钮集不再正常工作,因为在此过程中没有发生按钮事件。


所以我的问题是,当我临时修改DOM时,如何保护此类绑定事件免遭垃圾回收?

注意!我不能做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>


Java脚本


$(function(){
    $("#buttonset").buttonset();
    $("#toggle").click(
        function(){
            if($(this).is(":checked"))
            {
                backup = $("#container").html();
                $("#container").html("");
            } else $("#container").html(backup);
        }
    )
});


可播放的版本

See this jsFiddle



我在接受的答案中使用了该想法,以便在应用buttonset()之前保存html内容,然后根据需要在保存的数据上每次重新应用buttonset()

最佳答案

更新:

这是更新的fiddle,与您的OP非常接近。基本思想是destroys 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();
        }

    })
});

07-24 09:37
查看更多