2017-10-20 6 views
0

幅の異なるいくつかの要素があります。私はそれぞれをループする必要があります、幅の幅を見つけ、その幅にすべてを設定します。すべての要素を幅の最も広い幅に設定する

<div id="mySet"> 
    <span>some content</span> 
    <span>more content</span> 
    <span>here content</span> 
</div> 

JS:

var widest = 0; 

$("#mySet span").each(function(){ 
    var this = $(this), 
     wdth = this.width(); 

    if(wdth > widest){ 
     widest = wdth; 

     $("#mySet span").each(function(){ 
      $(this).width(widest); 
     }); 
    } 

}); 

私は最大幅を取得しますが、私のループに各要素に幅を割り当てるたびに行うことができると思います。あまりにも多くのループのようです。すべてspanに幅を設定するには

答えて

1

代替。

+0

省略記号は何をしますか? – santa

+1

この場合、mapによって返された配列の各幅をとり、それぞれをmax関数の別々の引数として渡します – searlea

2

、あなただけ

$("#mySet span").width(widest); 

に必要な、これはすべての幅を設定します。それで、ループの外側と最後に置きます。一度にすべてのスパンの幅を設定する

// Using modern JavaScript: 
const widest = Math.max(...$("#mySet span").map((i, span) => $(span).width())); 

// Using older JavaScript: 
var widest = Math.max.apply(
    null, 
    $("#mySet span").map(function() { 
    return $(this).width(); 
    }) 
); 

そして$("#mySet span").width(widest);:最も広いを取得するために、ループに

関連する問題