2011-10-23 36 views
0

我在一個ul和一個按鈕中有5個li。點擊按鈕,我想添加一個類到第一個li,然後在第二個點擊從第一個li刪除這個類,並添加它也是第二個ect。我知道我可以給每個人一個個人身份證,但我知道必須有更好的方式,我可能希望它在某些時候也是動態的。向Jquery一次添加一個類的一個類

在此先感謝。

回答

2

這裏是一個有效的解決方案:http://jsfiddle.net/PFpaU/

搭配點評:http://jsfiddle.net/PFpaU/1/

JS:

window.change = function() { 
    // Select any li which already has the class 
    var li = $("li.myclass"); 
    // If there were any matches... 
    if (li.length) 
     // Remove the class from the matched li and then move to the 
     // next item in the DOM tree, then add the class to that item 
     li.removeClass("myclass").next().addClass("myclass"); 
    else 
     // If none of the li's had the class, add it to the first one 
     $("li").first().addClass("myclass"); 
} 

HTML:

<ul> 
    <li>1</li> 
    <li>2</li> 
    <li>3</li> 
    <li>4</li> 
    <li>5</li> 
</ul> 
<button onclick="change()">Change</button> 

CSS:

.myclass { 
    color: #f00; 
} 
+0

完美,謝謝先生。 –

+0

你能解釋一下這個代碼嗎,我在next()方法的工作方式上遇到了問題。 –

+0

在你的代碼中,你不需要像我一樣聲明'change'函數。 'function change(){'會做得很好。在jsFiddle你必須像那樣宣佈他們。 –

0

你可以這樣做,

$('#yourButton').click(function(){ 
    var ul=$('#yourUlId'); 
    var next= $('li:not(.yourClass)',ul).first(); 
    next.addClass('yourClass'); 
    next.prev().removeClass('yourClass'); 
}); 
+0

您不是按照問題中所述刪除類。這也看全球所有'li'元素,而不是特定於列表。 –

+0

是的,我現在編輯它。 –

0

你要細化選擇比li更具體的東西,但是這應該做的伎倆(放置在您單擊處理程序)。

var withClass = $('li .your-class'); 

if (!withClass.length) { 
    // If nothing has the class, add to the first list element 
    $('li').addClass('your-class'); 
} else { 
    // Otherwise remove the class and add to the next item 
    withClass.removeClass('your-class').next().addClass('your-class'); 
} 
+0

嗨,這個添加是所有李的類。 –

+0

哎呦。當然你是對的。 if語句的第一個分支應該是'$('li')。first()'。其他一切應該工作得很好。 –

1

使用以下代碼。首先,您要選擇根元素<ul>(萬一存在多個元素)。然後,搜索一個包含您的課程名稱的列表元素,例如className。如果存在(li.length),請從當前列表中刪除該類,並將其添加到下一個。否則,將該類添加到<ul>的第一個列表元素。

$("#buttonID").click(function(){ 
    var ul = $("ul"); //Root <ul>, change it to the desired UL, eg #myUL 
    var li = $("li.className", ul); 
    if(li.length){ 
     li.removeClass("className").next().addClass("className"); 
    } else { 
     $("li", ul).addClass("className"); 
    } 
})