将函数/样式应用于每个()迭代

时间:2016-07-15 18:07:54

标签: javascript jquery html css

所以我得到了一个循环遍历每个' .related__item'并检查它是否包含图像(使用' .related__item-image')。如果为true,请使用正确的函数来计算每个' .related__item'的文本高度。并触发dotdodot功能。

我的问题是,它是通过每个“.related__item'正确和console.logs正确的true或false取决于图像。但由于某种原因,它为 ALL 相关项目提供了相同的高度。所以我相信在if语句中的某个地方出现了问题,但我无法弄清楚到底是什么。

我怎样才能做到这一点,以便每次迭代,循环给出一个真或假,为所有元素设置正确的高度 然后 继续下一个并做同样的事情。我是在考虑制作每个中的每一个吗?

Jfiddle:https://jsfiddle.net/bwbeLbnv/

OR

JS:

  var self = this;
  var textBlock = $('.text', self);
  var titleHeight = $('.related__item-title', self).outerHeight(true);
  var containerHeight = $('.related__item', self).outerHeight();
  var imageHeight = $('.related__item-image', self).outerHeight();
  var relatedItems = $(".related-magazines .related__item");

  var calculate_with_image = function() {
    var totalHeight = titleHeight + imageHeight;
    textBlock.css({height: containerHeight - totalHeight});
    textBlock.trigger("update.dot");
  };

  var calculate_without_image = function() {
    textBlock.css({height: containerHeight - titleHeight});
    textBlock.trigger("update.dot");
  };


  var related_resize = function() {
    for ( var i = 0; i < relatedItems.length; i++ ) {
      var element =  relatedItems.eq(i);
      var hasImage = element.find('.related__item-image', self).length === 1;
      console.log($(element).text());
      console.log(hasImage);

      if (hasImage === true) {
        calculate_with_image();
        console.log('IMAGE');

      } else if (hasImage === false) {
        calculate_without_image();
        console.log('TEXT');
      }
    }
  };

  related_resize();

HTML :(剥离)

<div class="related-magazines"> <!-- container -->   
 <div class="content"> <!-- inner container -->

    <div>
      <h3>Related pages</h3>
    </div>

    <!-- first column group -->
    <div class="field-name-sections first"> 

    <!-- related item w/ image -->
      <div class="related__item hni-grid first">
          <div class="related__item-section">
            <a href="link/url">
              <div class="related__item-image">
                <img class="item" src="img/url">
              </div>
              <div class="body">
                <div class="related__item-title">
                  <h4>
                    This is a title
                  </h4>
                  <h5 class="related-magazine-title">
                    This is a subtitle
                  </h5>
                </div>
                <div class="text">
                  This is a long description. etc etc etc.
                </div>
              </div>
            </a>
          </div>
        </div>

        <!-- related item w/o image -->
        <div class="related__item last">
          <div class="related__item-section">
            <a href="link/url">
              <div class="body">
                <div class="related__item-title">
                  <h4>
                    This is a title
                  </h4>
                  <h5 class="related-magazine-title">
                    This is a subtitle
                  </h5>
                </div>
                <div class="text" data-padding-bottom="1">
                  This is a long description. etc etc etc.
                </div>
              </div>
            </a>
          </div>
        </div> 

    </div>

    <!-- second column group -->
    <div class="field-name-sections last">

      <!-- related item w/ image -->
      <div class="related__item">
        <div class="related__item-section">
          <a href="link/url">
            <div class="related__item-image">
              <img class="item" src="image/url">
            </div>
            <div class="body">
              <div class="related__item-title">
                <h4>
                  This is a title
                </h4>
                <h5 class="related-magazine-title">
                  This is a subtitle 
                </h5>
              </div>
              <div class="text">
                This is a long description. etc etc etc.
              </div>
            </div>
          </a>
        </div>
      </div>

      <!-- related item w/ image -->
      <div class="related__item">
        <div class="related__item-section">
          <a href="link/url">
            <div class="related__item-image">
              <img class="item" src="image/url">
            </div>
            <div class="body">
              <div class="related__item-title">
                <h4>
                  This is a title
                </h4>
                <h5 class="related-magazine-title">
                  This is a subtitle
                </h5>
              </div>
              <div class="text">
                This is a long description. etc etc etc.
              </div>
            </div>
          </a>
        </div>
      </div>

    </div>

  </div> <!-- end content --> </div> <!-- end related magazines -->

2 个答案:

答案 0 :(得分:1)

如果我理解正确,这是因为calculate_with_image()里面的imageHeight变量应该是在循环中找到的特定图像的高度吗?

编辑:您拥有并正在使用的imageHeight变量仅适用于找到的一张图片。它不会根据您在循环中找到的内容进行更新。将循环中的高度或图像传递给calculate_with_image()(如下所述)可以解决问题。

如果是这种情况,你需要将循环中找到的元素传递给calculate_with_image()或高度,如下所示:

// calculate_with_image function
var calculate_with_image = function(element) {
    var elementImageHeight = element.find('.related__item-image', self).outerHeight();
    var totalHeight = titleHeight + elementImageHeight;
    textBlock.css({height: containerHeight - totalHeight});
    textBlock.trigger("update.dot");
};

// if statement found within your loop.
if(hasImage === true){
    calculate_with_image(element); // option one, pass the element
    console.log('IMAGE');
} // carry on with else if

OR

// calculate_with_image function
var calculate_with_image = function(elementImageHeight) {
    var totalHeight = titleHeight + elementImageHeight;
    textBlock.css({height: containerHeight - totalHeight});
    textBlock.trigger("update.dot");
};

// if statement found within your loop.
if(hasImage === true){
    var elementImageHeight = element.find('.related__item-image', self).outerHeight();
    calculate_with_image(elementImageHeight);
    console.log('IMAGE');
} // carry on with else if

这样,您的calculate_with_image将知道您想要处理的特定图像的高度。两种方法都有效。这只是一个问题,你是否喜欢在功能中可用的元素(找到的特定图像),或者只是你需要的高度。

答案 1 :(得分:1)

  

好吧,我已经删除了整个HTML结构,让您了解它的外观。

Thanx,这确实有帮助。您的代码中的问题是calculate_with_image()calculate_without_image()根本不考虑当前的.related__item。在循环之前计算这些函数中使用的所有值。这就是为什么它们为每次迭代返回相同的值。

评论:大多数jQuery方法计算/返回一个值而不对jQuery选择中的节点应用某些东西,从第一个DOM-Node计算此值。选择。因此$('.related__item-image').outerHeight()首先从文档中提取所有.related__item-image个节点,但仅返回第一个节点的outerHeight()

这是你的代码中出错的一件事。

我不确定这是否是您的意图,但我认为您首先尝试获取所有相关节点,然后迭代这些列表(我的意思是这部分:var textBlock = $('.text')和以下行)。如果这些列表之间存在1:1的关系,那么(不好,但确定)。如果没有,你会陷入混乱;所以一般情况下尽可能避免这种方法事情可能会出错很容易。或者可能会改变然后出错。
如果我在这里弄错了你的意图,别介意。

我无法测试下面的代码产生预期的结果,因为它取决于你的CSS,但我认为它应该做的工作:(否则,你会告诉我什么是错的)

$(".related-magazines .related__item").each(function(){
    //comment: jQuery iterators provide the current Element as `this`
    var $this = $(this);    //the current item wrapped in a jQuery-object.
    var containerHeight = $this.outerHeight();  //the height of this particular item

    //fetch the related image, and get it's outerHeight
    //returns `null` if no image is found, wich then will be replaced with a 0
    var imageHeight = $this.find('.related__item-image').outerHeight() || 0;
    //same for the related title:
    var titleHeight = $this.find('.related__item-title').outerHeight(true) || 0;    
    //btw, this would also work:
    //var imageHeight = $('.related__item-image', this).outerHeight() || 0;
    //and I mean `this` and not your cached `self`, but not your combination of find and self.

    console.log($this.text());
    console.log(imageHeight > 0);

    //inlined `calculate_with_image()` and `calculate_without_image()` because they are short, 
    //and almost identical, and need access to the same Nodes that are used 
    //comment: jQuery allows method-chaining
    $this.find('.text') //get the textBlock
        .height( containerHeight - (titleHeight + imageHeight) )    //set it's height
        .trigger("update.dot");     //and trigger

    console.log(imageHeight > 0? "IMAGE": "TEXT");
});

有人可能会说imageHeight > 0是不准确的,当测试是否有图像时。因为可能有一个图像,但高度为0.嗯,是的,但是这个计算不会有任何区别。

图像可能存在问题,导致此高度为0.可能它尚未加载,或者其中一个父项是display:none,但处理该问题将成为不同SO的主题-Question。