2011-09-08 18 views
1

我想遍歷元素。每個元素具有項目元素作爲子元素。因此,首先我重複,然後我想解決某個item元素,例如,第三。這是我的代碼:jQuery:如何解決具有特殊類的子項目

$(".pricetable .righttable .line:not(.blank)").each(function(j) { 
    var currentLine = $(".pricetable .righttable .line:not(.blank)").eq(j); 
    currentLine.(".item").each(function(k) { 
     $(".pricetable .righttable .line .item").eq(i).addClass("active"); 
    }); 
}); 

的問題是,我不知道如何解決與項目類的子元素。

currentLine.(".item").each(function(k) 

這是行不通的。對於非XML值({0:#2 =({}),長度:1,prevObject:{length:3,prevObject:{0:#1 =({}),上下文:#1#,長度:1},上下文:#1#,選擇器:「。pricetable .righttable .line:not(.blank)」,0:#2#,1 :({}),2: }),context:#1#,selector:「。pricetable .righttable .line:not(.blank).slice(0,1)」}) file:/// C:/ Users/xxx/lib/pricetable.js 112 線

編輯:
哇,我沒想到我得到這樣一個良好的和快速的響應!我覺得我跟這個解決方案:

$(".pricetable .righttable .line:not(.blank)").each(function(j) { 
    $(this).children(".item").eq(i).addClass("active"); 
}); 

回答

3
$(".pricetable .righttable .line:not(.blank)").each(function(j) { 
    var currentLine = $(".pricetable .righttable .line:not(.blank)").eq(j); 
    currentLine.find(".item").each(function(k) { 
     $(".pricetable .righttable .line .item").eq(i).addClass("active"); 
    }); 
}); 

http://api.jquery.com/find/

如果他們currentLine的直接孩子,你應該能夠做到children('.item')代替find('.item')。這被稱爲遍歷DOM。訪問此頁面(http://api.jquery.com/category/traversing/)並閱讀其中一些功能的描述。如果你遍歷了很多:)

2
$('.pricetable .righttable .line:not(.blank)').find('.item').each(function() { 
    // this point to child element - item 
    // use $(this).addClass('active'); 
}); 
2

如果你想要做的事,每個line的第n個item,它比它看起來要容易得多,他們會牢記非常有用:

var index = 3; // the third "item" element 
$(".pricetable .righttable .line:not(.blank) .item:nth-child(" + index + ")") 
    .addClass("active"); 

See it in action

是否還有其他想要做的事情,以上是不夠的?

2

略有改善我回答你的問題:

var currentLine = $(".pricetable .righttable .line:not(.blank)").eq(j); 

易於更換有:

var currentLine = $(this); 

第二,如果你想找到的$(this)內第三.item元素,使用.find()

.find(".item:nth-child(3)"); 

不需要遍歷行。如果你必須遍歷線,那麼只需比較k2(因爲JavaScript從0開始計數)就是這樣。

1
$(".pricetable .righttable .line:not(.blank)").each(function() { 
    $(this).find('.item:nth-child(2)').addClass('active'); 
}); 
相關問題