在运行脚本

时间:2017-01-10 17:55:09

标签: jquery settimeout

两天搜索所有相关帖子但没有成功。 我的代码使用本地存储来刷新页面时存储和检索复选框的状态。这很好用。我已经扩展了我的代码,将复选框加载到外部HTML文件的div中,这导致了计时问题。管理本地存储的代码运行得太快,无法将复选框加载到div中。延迟代码的许多努力都失败了,我最近的努力是'setTimeout',它没有预期的效果(见小提琴)。顺便说一句,如果有足够的“警报”停止代码,我已经证明所有这些都可以工作。请帮助我找到最好的方法。非常感激。 https://jsfiddle.net/Ldn2awxb/

https://code.jquery.com/jquery-2.2.3.min.js


<div id="CountryCheckboxContainer">

<!--      Checkboxes below are loaded from external HTML file   

   <label><input type="checkbox"  id="UN8" value="Albania" />Albania</label>
   <label><input type="checkbox"  id="UN40" value="Austria" />Austria</label>
   <label><input type="checkbox"  id="UN100" value="Bulgaria" />Bulgaria</label>
-->
</div>




// Load from external files
function LoadCheckboxes() {
setTimeout(function()
  { $("#CountryCheckboxContainer").load( "https://c2ect538.caspio.com/dp.asp?AppKey=b8a94000b0cf30c15313458e91a0");
  }, 500);
}


// set and get items
$(function() {

LoadCheckboxes();

  var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
    $checkboxes = $("#CountryCheckboxContainer :checkbox");

  $checkboxes.on("change", function() {
    $checkboxes.each(function() {
      checkboxValues[this.id] = this.checked;
    });
    localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
  });

  // On page load
  $.each(checkboxValues, function(key, value) {
    $("#" + key).prop('checked', value);
  });
});

2 个答案:

答案 0 :(得分:2)

.load()提供了提供成功完成时调用的回调函数的选项。不要将.load()用作设置的一部分,而是将设置设置为.load()

的一部分
$(function(){
  function setupCheckboxes(){
    var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
    $checkboxes = $("#CountryCheckboxContainer :checkbox");

    $checkboxes.on("change", function() {
      $checkboxes.each(function() {
        checkboxValues[this.id] = this.checked;
      });
      localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
    });

    $.each(checkboxValues, function(key, value) {
      $("#" + key).prop('checked', value);
    });
  };

  $("#CountryCheckboxContainer").load( "https://c2ect538.caspio.com/dp.asp?AppKey=b8a94000b0cf30c15313458e91a0", setupCheckboxes);
});

答案 1 :(得分:0)

我认为最好的方法是加载你的内容,然后调用绑定。像这样:

$.ajax({
  url: 'https://c2ect538.caspio.com/dp.asp?AppKey=b8a94000b0cf30c15313458e91a0',
  success: function(content){
     $("#CountryCheckboxContainer").html(content);
     //Put your behaviors here.
  }
})

您也可以通过这种方式同步执行代码。像这样:

$.ajax({
  url: 'https://c2ect538.caspio.com/dp.asp?AppKey=b8a94000b0cf30c15313458e91a0',
  async: false, //It makes stops JS execution in the page,
  success: function(content){
    $("#CountryCheckboxContainer").html(content);
  }
})
//And just keep your normal code.

如果您正在执行其他重要的JS内容,例如Google分析或引导程序,那么它将成为一个问题,并且在第一个选项方面要好得多。