【问题标题】:Restore page content and retain event listeners恢复页面内容并保留事件监听器
【发布时间】:2013-09-05 00:09:21
【问题描述】:

您将如何将页面“保存”到某个位置(在客户端),然后在其所有事件侦听器完好无损的情况下恢复它?

我在http://jsfiddle.net/KellyCline/Fhd55/ 有一个示例,它演示了我如何创建“页面”,将其保存并在单击按钮时转到“下一页”,然后在单击另一个按钮时恢复第一页,但现在第一个页面的点击监听器消失了。

我知道这是由于 html() 执行的序列化,所以,很明显,这是我做错了,但我想要的是做正确的线索。

这是代码:

    var history = [];

$(document).ready(function () {
    var page1 = $(document.createElement('div'))
        .attr({
        'id': 'Page 1'
    }).append("Page ONE text");
    var nextButton = $(document.createElement('button'));
    nextButton.append('NEXT');
    nextButton.on('click', function () {
        CreateNextPage();
    });
    page1.append(nextButton);
    $("#content").append(page1);
});

function CreateNextPage() {
    history.push( $("#content").html( ) );
    $("#content").html( 'Click Me!');
    var page1 = $(document.createElement('div'))
        .attr({
        'id': 'Page 2'
    }).append("Page TWO text");
    var nextButton = $(document.createElement('button'));
    nextButton.append('NEXT');
    nextButton.on('click', function () {
        CreateNextPage();
    });
    var prevButton = $(document.createElement('button'));
    prevButton.append('PREVIOUS');
    prevButton.on('click', function () {
        GoBack();
    });
    page1.append(nextButton);
    page1.append(prevButton);
    $("#content").append(page1);

}

function GoBack() {
    $("#content").html( history[history.length - 1]);
    history.pop( );
}

这是html:

点击我!

【问题讨论】:

    标签: javascript event-listener


    【解决方案1】:

    我认为这最好通过事件委托来解决。基本上,您将您知道将要刷新的内容封装在一个包装器元素中,并将您的侦听器绑定到它。 jQuery .on() 方法允许您将选择器字符串作为过滤器传递,并且只有在原始元素匹配时才会触发处理程序。给你的按钮一个类或其他东西来处理它们,然后将它们绑定在上面。 This article 有一些例子。

    $( '#content' ).on( 'click', 'button.next', createNextPage )
    

    例如。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-30
      相关资源
      最近更新 更多