2012-06-29 61 views
0

當我做 $('ul.latestnews ul li').parent().prev().text());我找回了目標li的內容。 (在這個例子中是word1或word2)。向孩子添加班級

但是當我做

$('ul.latestnews ul li').addClass($(this).parent().prev().text()); 

它不添加類。當我在最後一個語句上做一個console.log時,它只是返回所有我想要添加類的li。

我所試圖做的是這樣的:

<ul class="latestnews"> 
    <li>word1</li> 
    <ul> 
     <li>my class should become word1</li> 
     <li>my class should become word1</li> 
    </ul> 
    <li>word2</li> 
    <ul> 
     <li>my class must become word2</li> 
    </ul>   
</ul> 

哪兒我去錯了嗎?

+0

什麼是'this' ..? –

+0

@Rob。窗口,我猜... – gdoron

+0

是不是HTML無效? –

回答

2

this只是裏面一個jQuery功能的DOM元素,像each

$('ul.latestnews ul li').each(function(){ 
    $(this).addClass($(this).parent().prev().text()); 
}); 

Live DEMO this在你的代碼可能是Window對象...

注意,這些種類的DOM遍歷prev,parent如果稍微改變了DOM結構,就可以非常容易地中斷,您可能想要使用基於元素類的其他選擇器。

+0

快速問題bruv'.addClass(文本)'這會實現什麼,這是什麼? ++ 1反正就啓示':)'生活! –

+0

@Tats_innit。我沒有得到你的問題,但生活很好... :) – gdoron

+0

Saweet Bruv,Rocking \ m /;我的意思是這樣做:'.addClass($(this).parent()。prev()。text());'它只是添加'word1 word2'作爲類或更多,':P' –

1

我想的HTML代碼是不完全正確,因爲它應該是這樣的:

<ul class="latestnews"> 
    <li>word1</li> 
    <li> 
     <ul> 
      <li>my class should become word1</li> 
      <li>my class should become word1</li> 
     </ul> 
    </li> 
    <li>word2</li> 
    <li> 
     <ul> 
      <li>my class must become word2</li> 
     </ul> 
    </li>   
</ul> 

則:

$("ul.latestnews ul > li").each(function(){ 
    var $this=$(this); 
    var className = $this.parents("li").first().prev().text(); 
    $this.addClass(className); 
}); 
+0

你是對的。這可悲的是joomla組件k2的默認輸出。我將製作一個修復此錯誤的新K2模板。 – Jarco

+0

這裏是jsfiddle:http://jsfiddle.net/bDNz8/ –

+0

替換'.parents(「li」)。first()'with =>'.closest('li')' – gdoron