0

私は次のコードを持っています

 <span class="numbers">
    <a href="#">20</a>, <a href="#">50</a>, <a href="#">100</a>
 </span>

クラス「numbers」は、位置の絶対要素であり、ページ内で複数回使用されます。

クラス「numbers」内のコンテンツは動的に変化します。したがって、子の合計幅をその親コン​​テナに適用する必要があります

このコードを試しましたが、機能しませんでした。

var totalWidth = 0;
$(".numbers").children('a').each(function() {
      totalWidth = totalWidth + $(this).width();
      $('.numbers').each(function(){$(this).css("width", totalWidth);});
});

しかし、totalWidth値0のみを取得しています。誰か助けてくれませんか..........?

http://jsfiddle.net/contactsreejesh/xP3mn/6/を参照してください

4

3 に答える 3

1

numbersまず、すべての要素をループする必要があります。次に、そのループ内で、個々のnumbersスパンに属する子をループします

$('.numbers').each(function() {
    var totalWidth = 0;
    /* "this" in this loop is the current numbers span*/
    var $self=$(this) 
   /* loop over all the children of this element*/
    $self.children('a').each(function() { 
        /* "this" in current loop is an A tag*/
        totalWidth += $(this).width();      
    });

    /* now set width*/
    $self.width( totalWidth)

})

このステートメントは、ページ全体のクラスを持つすべての要素に影響し、それらはすべて同じ幅になります

$('.numbers').width(totalWidth); 
于 2012-11-14T22:13:17.770 に答える
0

これはここのように私のために働きます

var w = 0;
$('.numbers').find('a').each(function(){
    w += $(this).width();
});​​​​​​
于 2012-11-14T22:06:46.640 に答える
0

このフィドルを確認してくださいhttp://jsfiddle.net/FGmYU/

変更はこれです:

totalWidth += $(this).width();

入力は、計算された幅が56であることを示しています。

于 2012-11-14T22:03:55.130 に答える