2017-02-10 25 views
1

我正在努力使用jquery檢索div數組中div的寬度。通常我會做這樣的事情...Jquery從列表中檢索特定div的寬度

$("#divID").width() 

這會工作得很好,但我度過這段時間的div的列表進行迭代,這將返回錯誤「未捕獲的類型錯誤:$(... )[0] .width不是函數「

$("#parentID .childClass")[0].width() 
$("#parentID .childClass")[1].width() 
etc... 

而使用.width(作爲屬性而不是函數)只返回」undefined「。

任何想法我做錯了什麼?我最初省略了.childClass標識符,這就是我的jquery選擇正確返回所有div的列表的原因。我的問題是真的只是如何回報這樣一個div的寬度

+0

請發表您的HTML –

+1

什麼,我看到的是你用相同的ID('parentID')的所有div。 –

+1

另外$(「#parentID」)[0]不是jQuery對象,使用eq()如果你想要 – Booboobeaker

回答

1

你必須使用eq,以便在指定索引。這裏得到div是一個例子:

EQ方法降低設定的匹配元素添加到指定索引處的元素。

var length=$('.parentClass').length; 
 
for(i=0;i<length;i++){ 
 
    console.log($('.parentClass').eq(i).width()); 
 
}
.parentClass{ 
 
    width:50px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="parentClass"></div> 
 
<div class="parentClass"></div>

另一種解決方案是使用each()方法。

$("#parentID .childClass").each(function(){ 
    //code 
}); 
1

你可以寫一個jQuery插件來做到這一點。只需在父元素中查找子元素並找到nᵗʰ項即可。

(function($) { 
 
    $.fn.nthChild = function(childSelector, n) { 
 
    return this.find(childSelector).eq(n); 
 
    }; 
 
    $.fn.nthChildWidth = function(childSelector, n) { 
 
    return this.nthChild(childSelector, n).width(); 
 
    }; 
 
})(jQuery); 
 

 
console.log($('#parent-id').nthChildWidth('.child-class', 0)); 
 
console.log($('#parent-id').nthChildWidth('.child-class', 1));
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="parent-id"> 
 
    <div class="child-class" style="width:200px"></div> 
 
    <div class="child-class" style="width:300px"></div> 
 
</div>