Art*_*dov 5 javascript jquery dom jquery-events
我正在为我的网站编写一个无限滚动的脚本:
$(window).scroll(function(){
  if($(window).scrollTop() == $(document).height() - $(window).height()){
    ...
    $.ajax({
      ...
      success: function(json) {if(json.success){
        ...
        // here I append an Ajax @response with a new element to my existing HTML
        $("#mindIndexSummaryFirst").append(json.items1);
        $("#mindIndexSummarySecond").append(json.items2);
        $("#mindIndexSummaryThird").append(json.items3);
        // here I try to check whether all images are loaded
        $("#mindIndexSummary img").on('load', function(){
          // and I need to call two functions on loaded element
          // hoverImg() need the loaded image to calculate the height
          $('.pi-hover-img'+json.course).hoverImg();
          $(".popup3").tooltip();
        });
      }
    ...
  });
加载的 HTML 元素是这样的:
<div class="page-item pi-hover-img  pi-normal">
  <a class="overlayPop" href="#">
  <a class="item_uri" id="course153" href="#">
    <img src="/public/file/course/image/153-course.png" class="pi-item-image">
  </a>
  <a href="#" class="popup5 hide-text" style="display: none;">
    <img src="/public/file/account/image/282-user.jpeg" class="item_image">
  </a>
  <a class="popup action-button big_interested " id="course_153" href="javascript:;" style="top: -162.5px; left: 83.5px; display: none;"> Mi interessa</a>
  <a href="javascript:;">Description</a>
  <a class="popup4 hide-text" href="javascript:;">Preview</a>
  <span class="popup2" style="display: none;">1€</span>
  <a href="/course/153/gestire-un-pubblico">
    <h2 style="top: 320px;">Gestire un pubblico</h2>
    <span class="rfloat pi-icon">
      <img src="/public/img/site_icon/video_course_black.png">
    </span>
    <div class="clearfix"></div>
  </a>
</div>
我加载了 5 个元素,15 个图像,但加载的元素可能较少。
问题是我的函数被调用了不止一次(我用警报测试了这一点),并且我不确定在图像加载后调用该函数是否安全。
如果有人有同样的情况,请给我一些建议(PS,我为我糟糕的英语道歉)。
$("#mindIndexSummary img").on('load', function(){ });
将处理程序附加到与查询匹配的每个图像 - 因此每个图像在加载时都会触发该函数 - 而不是在所有图像加载完成时触发一次。
您必须跟踪已加载的图像才能判断它们是否已全部加载。
沿着以下路线:
var noOfImages = $("#mindIndexSummary img").length;
var noLoaded = 0;
$("#mindIndexSummary img").on('load', function(){ 
    noLoaded++;
    if(noOfImages === noLoaded) {
        handleAllLoaded();
    }
});
| 归档时间: | 
 | 
| 查看次数: | 8053 次 | 
| 最近记录: |