使用Jquery一次向一组li添加一个类

时间:2011-10-23 14:25:47

标签: jquery html

我有一个ul和一个按钮的5个li。单击按钮我想在第一个li中添加一个类,然后在第二个单击中从第一个li中删除该类,并将其添加到第二个类中。我知道我可以给每个人一个个人身份,但我知道必须有一个更好的方法,我可能希望它在某些时候也是动态的。

提前感谢。

4 个答案:

答案 0 :(得分: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;   
}

答案 1 :(得分: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");
    }
})

答案 2 :(得分:0)

你可以这样做,

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

答案 3 :(得分: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');
}