【问题标题】:How to only append once when loading in html Ajax在html Ajax中加载时如何只附加一次
【发布时间】:2013-03-16 18:42:09
【问题描述】:

我从我创建的灯箱中的 JSON 文件加载内容。灯箱打开另一个 html。在该 html 中,我将从 JSON 文件加载的数据附加到各种元素。但是我只想在他们打开灯箱时追加一次,我该怎么做?

$(document).on('click', '.mch-overlay-info', function(e){
    e.preventDefault();
    var href = $(this).attr('href');
    $('#mch-overlay-content').html('');
    $('#mch-overlay').fadeIn(300);
    $('#mch-overlay-content').load(href, function() {
        showInfo(); 
    });
});

function showInfo(){

        $(".start .text3").append(data[lang]['startpage']['text3']);
        $(".start .text4").append(data[lang]['startpage']['text4']);
        $(".start .text5").append(data[lang]['startpage']['text5']);

}

【问题讨论】:

    标签: ajax json append


    【解决方案1】:

    我假设您的问题是每次点击它都会附加?两种选择:

    1. 不要附加它。只需使用$().html() 设置内容并替换旧内容即可。
    2. 用变量控制

      var hasBeenAppended = false;
      
      //etc...
      
      function showInfo(){
          if(!hasBeenAppended) {
              hasBeenAppended = true;
              $(".start .text3").append(data[lang]['startpage']['text3']);
              $(".start .text4").append(data[lang]['startpage']['text4']);
              $(".start .text5").append(data[lang]['startpage']['text5']);
          }
      
      }
      

    【讨论】:

    • 谢谢老板!用 append 而不是 .html 让我很愚蠢,干杯!
    猜你喜欢
    • 1970-01-01
    • 2011-09-15
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多