[英]Can anyone explain this nested each behavior to me?
<html>
<body>
<div class="img-container">8
<div class="product">
<ul class="sizeAvail" style="display:none;">
<li><a href="one"></a>7</li>
<li><a href="one"></a>7</li>
<li><a href="one"></a>7</li>
<li><a href="one"></a>7</li>
<li><a href="one"></a>7</li>
</ul>
</div>
</div>
<div class="imgblock">7
<div class="product">
<ul class="sizeAvail" style="display:none;">
<li><a href="one"></a>8</li>
<li><a href="one"></a>8.5</li>
<li><a href="one"></a>9</li>
<li><a href="one"></a>9.5</li>
</ul>
</div>
</div>
<div class="imagearea">6
<div class="product">
<ul class="sizeAvail" style="display:none;">
<li>7</li>
<li>6.5</li>
<li>7</li>
<li>8</li>
</ul>
</div>
</div>
</body>
這是javascript:
$(".img-container").each(function(){
$(".product").each(function () {
$(".sizeAvail li").each(function () {
$(this).parent().show();
});
});
});
我希望只在第一個div上得到這樣的東西,因為它是唯一一個與類匹配的div:
8 7 7 7 7 7
但是我得到了..本質上嵌套了在所有div上運行的每個函數:8 7 7 7 7 7 7 8 8.5 9 9.5 6 7 6.5 7 8
這是jFiddle的鏈接:
我真正的最終目標是獲取所有href值,但我一直努力達到目標並陷入困境。
任何幫助表示贊賞!
您嵌套的.each()
實際上並沒有做任何事情來過濾您的選擇。 您需要一個$(this).
只找到父母的那些孩子。
$(".img-container").each(function(){
$(this).find(".product").each(function () {
$(this).find(".sizeAvail li").each(function () {
$(this).parent().show();
});
});
});
在您的示例中,您實際上是在所有元素上嵌套了for () loop
。
您的javascript不同於:
$(".sizeAvail li").each(function () {
$(this).parent().show();
});
除了由於嵌套循環而重復執行該操作。
如果要專門在先前循環的范圍內進行搜索,則需要添加選擇器上下文 。
$(".img-container").each(function () {
$(".product", $(this)).each(function () {
$(".sizeAvail li", $(this)).each(function () {
$(this).parent().show();
});
});
});
小提琴: http : //jsfiddle.net/TGXsk/10/
嘗試這個:
$(".img-container").each(function(){
$(this).find(".product").each(function () {
$(this).find(".sizeAvail li").each(function () {
$(this).parent().show();
});
});
});
您在這里做錯了。 在您的代碼中:
$(".img-container").each(function(){/* Select all elements with "img-container" class */
$(".product").each(function () {/* Select all elements with "product" class (not only child of "img-container" div ) */
$(".sizeAvail li").each(function () {/* Select all child li elements with-in "sizeAvail" class */
$(this).parent().show();
});
});
});
如您所述:您只想顯示具有“ img-container”的第一個div,因此,您需要像這樣修改代碼-
$(".img-container .product .sizeAvail li").each(function(){
$(this).parent().show();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.