HTML< ul> |更改特定的< li>为onclick和其他< li>颜色在同一< ul>中默认颜色 [英] HTML <ul> | Change particular <li> color onclick and other <li> in the same <ul> to default color

查看:59
本文介绍了HTML< ul> |更改特定的< li>为onclick和其他< li>颜色在同一< ul>中默认颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有5个列表,例如单击它们时,它们变为绿色,而如果其他任何列表为绿色,则将其他列表变为黑色.

I want to have 5 lists such than when any of them is clicked, it turns to green and turn the other lists to black if any of them is green.

这是我的清单:

<div id="menu">
    <ul>
        <li>one</li>
        <li>two</li>
        <li>three</li>
        <li>four</li>
        <li>five</li>
    </ul>
</div>

我写了jquery.但是,这并不简洁,因为我必须选择$('#menu li:first-child').. and $('#menu li:nth-child(2 to 5)')..

I have written the jquery. However, it's not concise, as I have to select $('#menu li:first-child').. and $('#menu li:nth-child(2 to 5)')..

请查看演示,并告诉我您完成此操作的最简单方法

Please check out the demo and let me know the easiest way you have to get this done

演示:

http://jsfiddle.net/t7L6d7b4/

推荐答案

您的操作方式:

var $li = $('#menu li').click(function() {
    $li.removeClass('selected');
    $(this).addClass('selected');
});

使用此CSS来选择项目:

with this CSS for selected item:

li.selected {
    color: green;
}

永远不要使用css方法,这是非常的强制性方法,需要在更改样式时修改JS代码.如果明天您决定将背景图像添加到所选项目,那么如果使用.css方法,您将要做什么?您应该为此使用类,在这种情况下,您只需编写一次JS,然后就不用管它了.样式用于CSS,UI逻辑用于JS.

Don't ever use css method for such things, this is very obtrusive approach which requires you to modify JS code when you want to change styling. If tomorrow you decide to add a background image to selected item, what will you have to do if you go with .css approach? You should use classes for this, in this case you write JS once and forget about this. Styles are for CSS, UI logic is for JS.

这是演示:

var $li = $('#menu li').click(function() {
    $li.removeClass('selected');
    $(this).addClass('selected');
});

li.selected {
    color: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="menu">
    <ul>
        <li>one</li>
        <li>two</li>
        <li>three</li>
        <li>four</li>
        <li>five</li>
    </ul>
</div>

这篇关于HTML&lt; ul&gt; |更改特定的&lt; li&gt;为onclick和其他&lt; li&gt;颜色在同一&lt; ul&gt;中默认颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆