2013-10-30 40 views
0

我只想問一下,我怎樣才能得到子元素的類。 例如,如果我有這樣的代碼:如何使用jquery獲取父類id的子類?

<a class="w010 h010 p007 b03 d2 f1" id="category_entertainment"> 
    <div class="it3 ib3 il3 jt05 jb05 jl10 kt04 kb04 kl03"> 
     //some codes here. . . 
    </div> 
</a> 

現在我有一個錨標記。我的場景是點擊標籤後。我需要獲得div的類並將其替換爲我的新類。

$("#category_entertainment").on('click',function(){ 

    var new_class = "it3 ir3 il3 jt10 jr05 jl05 kt03 kr04 kl04"; 

    $("#category_entertainment > div).attr("class",new_class); //i tried this but not working. 

}); 
+4

您需要關閉您的報價上的選擇:'$( 「#category_entertainment> DIV」)' –

+0

啊確定。語法錯誤。 :)謝謝 – Jerielle

+0

Javascript錯誤控制檯將允許你看到和調試這樣的錯誤。以下是如何在[Mozilla](https://developer.mozilla.org/en-US/docs/Tools/Web_Console),[Chrome](https://developers.google.com/chrome-developer-tools)中打開它/ docs/console#opens_the_console)和[Safari](http://gardengnomesoftware.com/wiki/Using_The_Browser_Error_Console#Safari)。 –

回答

0

這工作正常我的機器上:

$("#category_entertainment").on('click',function(){ 

    var new_class = "it3 ir3 il3 jt10 jr05 jl05 kt03 kr04 kl04"; 

    $("#category_entertainment div").attr("class",new_class); 

}); 

我唯一的建議是,以確保該代碼居留權運行已創建的元素之後。如果你把它放在window.onload=function() {// assign click handler}之類的東西中,以確保元素被加載。下面是一個jsfiddle的例子。

jsfiddle example

+0

好吧,我這樣做,但它影響我的其他div標籤。 :( – Jerielle

+0

@RochelleCanale其他'div'標籤? –

+0

我還有另一個div標籤,就像我的代碼一樣,這是同一個class name。 – Jerielle