因为循环不能像我期望的那样工作

时间:2016-10-19 21:50:57

标签: javascript jquery loops for-loop

很抱歉这里的人不清楚。感谢您的快速回复。

我希望使用这段js来均衡各种div的高度。它似乎适用于类“jsEq-1”的div(显示在我的片段中的红色框中。

我也期待绿色和黄色的盒子在高度上均衡......所以所有的绿色盒子都是相同的高度,所有的黄色盒子都是相同的高度。因此,尽管每个盒子中的内容长度不同,但我希望容器具有相同的高度和排列的所有内容。

绿色框有一个jsEq-2类,黄色框有一个jsEq3类但我的脚本似乎不适用于类为“jsEq-2”或“jsEq-3”“jsEq4”的div等等。

我希望它循环遍历任何以“jsEq-”开头的类,以及最后的任何数字,但我无法理解这一点。

提前感谢任何提示。

$(window).load(function() {

    $.fn.extend({
        equalHeights: function(){
            var top=0;
            var row=[];
            var classname=('equalHeights'+Math.random()).replace('.','');
            $(this).each(function(){
                var thistop=$(this).offset().top;
                if (thistop>top) {
                    $('.'+classname).removeClass(classname);
                    top=thistop;
                }
                $(this).addClass(classname);
                $(this).height('auto');
                var h=(Math.max.apply(null, $('.'+classname).map(function(){ return $(this).outerHeight(); }).get()));
                $('.'+classname).outerHeight(h);
                //$('.'+classname).css("min-height",(h));
            }).removeClass(classname);
        }
    });

    var equalizeMe = function() {
        var $highest = 1;
        $("[class^='jsEq-']").each(function(idx,ele){
            var $classname = $(this).attr("class");
            var $parts = $classname.split("-");
            if($highest < $parts[1]){
                $highest = $parts[1];
            }
        });

        for(var $i=1; $i<$highest+1; $i++){
            $(".jsEq-"+$i).equalHeights();
        }
    };

    //------------------------------------------------------
    // VIEWPORT RESIZING
    $(window).resize(function () {
        equalizeMe();
    }).trigger("resize");

});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
h2, p {
  margin-bottom: 0;
}

.column {
  float: left;
  width: 30%;
  margin: 0 1%;
  background: blue;
}

.header {
  background: red;
}

.body {
  background: green
}

.footer {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<div class="column">
	<div class="header jsEq-1">
		<h2>Short heading</h2>
	</div>
	<div class="body jsEq-2">
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas metus sapien, vulputate eget molestie eu, ultricies sit amet urna. Donec mollis pharetra tortor, nec sollicitudin ligula sodales vel. Duis feugiat id nunc a maximus. Nulla pretium lorem eu justo tincidunt, eget faucibus ex egestas. Aliquam commodo enim at lorem blandit sodales. Aenean sed tellus vitae nisl imperdiet molestie eget id mauris. Praesent non ullamcorper sapien.</p>
	</div>
	<div class="footer jsEq-3">
		<p>Duis feugiat id nunc a maximus.</p>
	</div>
</div>

<div class="column">
	<div class="header jsEq-1">
		<h2>Medium heading blandit id sollicitudin eget, pellentes</h2>
	</div>
	<div class="body jsEq-2">
		<p>Pellentesque quam augue, blandit id sollicitudin eget, pellentesque in nunc. Curabitur sed purus justo. Maecenas aliquet, purus non porta vestibulum, dolor nisi congue nisi, id tincidunt quam nisi non lacus. Morbi in nunc eget neque rhoncus dapibus. Morbi id orci ligula. Duis elementum, sem eget tempus bibendum, est purus vestibulum felis, ut aliquam sem felis id massa. Aliquam non imperdiet ligula, vitae laoreet nisl. Fusce vehicula metus nec lectus luctus tempor. Integer laoreet ligula quis magna dignissim, sed convallis tellus finibus. Mauris arcu justo, dignissim congue maximus vel, faucibus eu ipsum. Duis ullamcorper mi in risus finibus fermentum. Pellentesque ut metus feugiat arcu ullamcorper elementum et sed nunc. Donec luctus diam a orci elementum, in sollicitudin mauris scelerisque. Morbi aliquet enim enim. Nullam quis pretium lectus. </p>
	</div>
	<div class="footer jsEq-3">
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas metus sapien, vulputate eget molestie eu, ultricies sit amet urna. Donec mollis pharetra tortor, nec sollicitudin ligula sodales vel. Duis feugiat id nunc a maximus.</p>
	</div>
</div>

<div class="column">
	<div class="header jsEq-1">
		<h2>Long heading pellentesque quam augue, blandit id sollicitudin eget, pellentesque in nunc</h2>
	</div>
	<div class="body jsEq-2">
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas metus sapien, vulputate eget molestie eu, ultricies sit amet urna. Donec mollis pharetra tortor, nec sollicitudin ligula sodales vel. Duis feugiat id nunc a maximus.</p>
	</div>
	<div class="footer jsEq-3">
		<p>Donec mollis pharetra tortor, nec sollicitudin ligula sodales vel. Duis feugiat id nunc a maximus.</p>
	</div>
</div>

3 个答案:

答案 0 :(得分:1)

此代码似乎工作正常。问题可能出在html,equalHeights函数或正在使用的jQuery版本中。

OP编辑后:选择器

$("[class^='jsEq-']")

正在使用^=,它只匹配以给定字符串开头的类名。由于您有其他首先出现的类名,因此您需要使用*=来选择其类名包含给定字符串的任何标记。

$("[class*='jsEq-']")

我也换了

var $parts = $classname.split("-");
if($highest < $parts[1]){
    $highest = $parts[1];
}

var $classNumber = parseInt($classname.substring($classname.indexOf("jsEq-")+5));
if($highest < $classNumber){
    $highest = $classNumber;
}

如果你有其他带有破折号的类(例如在bootstrap中非常常见),这会更安全。

&#13;
&#13;
var equalizeMe = function() {
    var $highest = 1;
    $("[class*='jsEq-']").each(function(idx,ele){
        var $classname = $(this).attr("class");

        // this extracts the number after 'jsEq'
        // otherwise, other dash-classes would break your split("-") array method
        var $classNumber = parseInt($classname.substring($classname.indexOf("jsEq-")+5));

        if($highest < $classNumber){
            $highest = $classNumber;
        }
    });

    for(var $i=1; $i<$highest+1; $i++){
        // This is showing the loop works. Check equalHeights()
        $(`.jsEq-${$i}`).html(`.jsEq-${$i} highest = ${$highest}`);
    }
};

equalizeMe();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test jsEq-1 foo foo-baz"></div>
<div class="text foo-bar jsEq-2"></div>
<div class="stuff jsEq-3"></div>
<div class="foo jsEq-4 dash-this"></div>
<div class="bar jsEq-5 dash-that"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

[class^='jsEq-']函数中的equalizeMe选择器定位的是具有以字符串jsEq-开头的类的元素,但不存在此类元素。你所有的&#34;班级&#34;值实际上以&#34; header&#34;,&#34; body&#34;或&#34; footer&#34;开头。

因此,$highest永远不会从其初始值1修改,因此后续的for循环只运行一次,这就是为什么只有红色框具有相同的高度。

要解决此问题,请定位其&#34;类&#34;值包含字符串&#34; jsEq - &#34;代替。

只需更改此行:

$("[class^='jsEq-']").each(function(idx,ele){

对此:

$("[class*='jsEq-']").each(function(idx,ele){


答案 2 :(得分:0)

谢谢你们

@MJH - 我最终在each()函数中移动for循环并更改为[class * ='jsEq-'],现在它似乎正常工作。请参阅更新的代码段。

$(window).load(function() {

    $.fn.extend({
        equalHeights: function(){
            var top=0;
            var row=[];
            var classname=('equalHeights'+Math.random()).replace('.','');
            $(this).each(function(){
                var thistop=$(this).offset().top;
                if (thistop>top) {
                    $('.'+classname).removeClass(classname);
                    top=thistop;
                }
                $(this).addClass(classname);
                $(this).height('auto');
                var h=(Math.max.apply(null, $('.'+classname).map(function(){ return $(this).outerHeight(); }).get()));
                $('.'+classname).outerHeight(h);
                //$('.'+classname).css("min-height",(h));
            }).removeClass(classname);
        }
    });

    var equalizeMe = function() {
        var $highest = 1;
        $("[class*='jsEq-']").each(function(idx,ele){
            var $classname = $(this).attr("class");
            var $parts = $classname.split("-");
            if($highest < $parts[1]){
                $highest = $parts[1];
            }

            for(var $i=1; $i<$highest+1; $i++){
                $(".jsEq-"+$i).equalHeights();
            }
        });
    };

    //------------------------------------------------------
    // VIEWPORT RESIZING
    $(window).resize(function () {
        equalizeMe();
    }).trigger("resize");

});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
h2, p {
  margin-bottom: 0;
}

.column {
  float: left;
  width: 30%;
  margin: 0 1%;
  background: blue;
}

.header {
  background: red;
}

.body {
  background: green
}

.footer {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<div class="column">
	<div class="header jsEq-1">
		<h2>Short heading</h2>
	</div>
	<div class="body jsEq-2">
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas metus sapien, vulputate eget molestie eu, ultricies sit amet urna. Donec mollis pharetra tortor, nec sollicitudin ligula sodales vel. Duis feugiat id nunc a maximus. Nulla pretium lorem eu justo tincidunt, eget faucibus ex egestas. Aliquam commodo enim at lorem blandit sodales. Aenean sed tellus vitae nisl imperdiet molestie eget id mauris. Praesent non ullamcorper sapien.</p>
	</div>
	<div class="footer jsEq-3">
		<p>Duis feugiat id nunc a maximus.</p>
	</div>
</div>

<div class="column">
	<div class="header jsEq-1">
		<h2>Medium heading blandit id sollicitudin eget, pellentes</h2>
	</div>
	<div class="body jsEq-2">
		<p>Pellentesque quam augue, blandit id sollicitudin eget, pellentesque in nunc. Curabitur sed purus justo. Maecenas aliquet, purus non porta vestibulum, dolor nisi congue nisi, id tincidunt quam nisi non lacus. Morbi in nunc eget neque rhoncus dapibus. Morbi id orci ligula. Duis elementum, sem eget tempus bibendum, est purus vestibulum felis, ut aliquam sem felis id massa. Aliquam non imperdiet ligula, vitae laoreet nisl. Fusce vehicula metus nec lectus luctus tempor. Integer laoreet ligula quis magna dignissim, sed convallis tellus finibus. Mauris arcu justo, dignissim congue maximus vel, faucibus eu ipsum. Duis ullamcorper mi in risus finibus fermentum. Pellentesque ut metus feugiat arcu ullamcorper elementum et sed nunc. Donec luctus diam a orci elementum, in sollicitudin mauris scelerisque. Morbi aliquet enim enim. Nullam quis pretium lectus. </p>
	</div>
	<div class="footer jsEq-3">
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas metus sapien, vulputate eget molestie eu, ultricies sit amet urna. Donec mollis pharetra tortor, nec sollicitudin ligula sodales vel. Duis feugiat id nunc a maximus.</p>
	</div>
</div>

<div class="column">
	<div class="header jsEq-1">
		<h2>Long heading pellentesque quam augue, blandit id sollicitudin eget, pellentesque in nunc</h2>
	</div>
	<div class="body jsEq-2">
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas metus sapien, vulputate eget molestie eu, ultricies sit amet urna. Donec mollis pharetra tortor, nec sollicitudin ligula sodales vel. Duis feugiat id nunc a maximus.</p>
	</div>
	<div class="footer jsEq-3">
		<p>Donec mollis pharetra tortor, nec sollicitudin ligula sodales vel. Duis feugiat id nunc a maximus.</p>
	</div>
</div>