【问题标题】:insertAfter inserting code twiceinsertAfter 插入代码两次
【发布时间】:2013-12-22 09:31:07
【问题描述】:

我正在尝试在我的网站中插入几行新代码。当浏览器宽度小于768px时需要插入代码,如果代码已经存在则不需要再次插入。出于某种原因,每当我将浏览器的大小调整为小于 768 时,代码都会插入两次,然后每次调整大小时再插入一次。有谁知道为什么这行代码被多次插入?

$(window).resize(function() {
  if ($(window).width() < 768) {
    if ($(document).not('#step-4-circle')) {
      $('<div id="step-4-circle" class="step-circle"><div class="inner"><span class="number">4</span><span class="title">FULFILL ORDERS</span><span class="subtitle">where you want</span></div></div>').insertBefore('#how-step-3');
    }
  }

});

【问题讨论】:

    标签: jquery insert resize insertafter


    【解决方案1】:

    调整条件以检查是否选择了任何元素:

    if ( $('#step-4-circle').length == 0 ) {
        $('<div id="step-4-circle" class="step-circle"><div class="inner"><span class="number">4</span><span class="title">FULFILL ORDERS</span><span class="subtitle">where you want</span></div></div>').insertBefore('#how-step-3');
    }
    

    JS 小提琴: http://jsfiddle.net/3zP8H/1/

    【讨论】:

      【解决方案2】:

      .not() 方法从集合中删除匹配的元素,$(document) 返回一个只有一个元素(文档对象)的集合,您试图排除 ID 为 step-4-circle 的不存在的元素在集合中。此外,作为一个对象是一个真实值,您的条件始终为真,您应该使用@Kevin 提到的length 属性。

      还要注意resize 事件被触发很多次,如果你想监听这个事件最好使用.setTimeout() 函数:

      var t = null; 
      var $w = $(window).resize(function() {
           clearTimeout(t); 
           t = setTimeout(function(){
               if ( $w.width() < 768 ) {
                    if ($('#step-4-circle').length == 0)
                    $('<div id="step-4-circle">...</div>').insertBefore('#how-step-3');
               } else {
                    $('#step-4-circle').remove();
               }
           }, 80);
      });
      

      【讨论】:

        猜你喜欢
        • 2015-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多