【问题标题】:Jquery localStorage not firing at first clickJquery localStorage 在第一次点击时没有触发
【发布时间】:2018-08-27 22:14:59
【问题描述】:

当我单击print-receipt 时,我想将子div 的类更改为receipt_finished。 然后我将localStorage 项替换为新的html 内容(包含receipt_finished 类)。

HTML

<div id="1" class="print-receipt no-print page-break printed">
    <div class="receipt_content"><span>1</span></div>
    </div>

JQUERY

$(document).on('click', '.print-receipt', function (e) {
            e.preventDefault();
            var receipt_id = $(this).attr('id');
            var receipt_html = $(this).html();
            $(this).find('.receipt_content').toggleClass("receipt_finished");
            localStorage.setItem('printer_' + printer_id + '_receipt_' + receipt_id, receipt_html);
            });

当我第一次刷新页面时,toggleClass 工作正常,但 localStorage.setItem 仅在 第二次点击 时工作。 所以代码工作如下:

第一次 div 点击:

html 中,它更改为&lt;div class="receipt_content receipt_finished"&gt;

localStorage 没有任何反应

第二次点击时:

html 中更改为&lt;div class="receipt_content"&gt;

localStorage 中,它更改为&lt;div class="receipt_content receipt_finished"&gt;

页面加载时或在此点击事件之前创建时,该项目已存在于localStorage中。

【问题讨论】:

    标签: jquery html local-storage


    【解决方案1】:

    更改切换类和获取 html 的顺序,以便在获取 html 时包含类更改

    $(document).on('click', '.print-receipt', function(e) {
      e.preventDefault();
      var receipt_id = $(this).attr('id');
      // toggle the class first
      $(this).find('.receipt_content').toggleClass("receipt_finished");
      // html will now have the class change
      var receipt_html = $(this).html();
    
      localStorage.setItem('printer_' + printer_id + '_receipt_' + receipt_id, receipt_html);
    });
    

    【讨论】:

    • 谢谢!那行得通,由于某种原因,我没有看到 :(((((((((()))
    猜你喜欢
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2015-08-22
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多