关于多个元素的jQuery ToggleClass

时间:2014-07-25 16:27:58

标签: jquery toggleclass

我需要在多个元素上切换一个类,并且无法弄清楚如何遍历dom并将其全部更改。我有一个静音 - 所有btn,当点击时,应该将所有静音图标变为红色。它目前只会将我点击的btn图标变成红色,但其他都没有。感谢。

<script>$(function() {
        $(".js_mute-all").click(function() {
            $(".icon-mute").toggleClass('red');
        });
    });</script>

HTML

<ul class="call-list">
        <li class="byself">
            <a href="#" class="btn btn-clear-white js_invite"><i class="icon-plus"></i> Invite Others</a> &nbsp; 
            <a href="#" class="btn btn-clear-white right js_mute-all"><i class="icon-mute"></i> Mute All</a>

            <form class="invite-others">
                <select>
                    <option>Select a person</option>
                </select>
                <input type="submit" value="Send" class="btn btn-clear-white" />
            </form>
        </li>
        <li>
            <p>Mary Jones</p>
            <span class="actions"><i class="icon-mute" alt="mute"></i> <i class="icon-forward_alt" alt="Make presenter"></i> <i class="icon-no" alt="Kick out from conversation"></i></span>
        </li>
        <li>
            <p>Ray Jackson</p>
            <span class="actions"><i class="icon-mute" alt="mute"></i> <i class="icon-forward_alt" alt="Make presenter"></i> <i class="icon-no" alt="Kick out from conversation"></i></span>
        </li>
        <li>
            <p>Joe Lazy</p>
            <span class="actions"><i class="icon-mute" alt="mute"></i> <i class="icon-forward_alt" alt="Make presenter"></i> <i class="icon-no" alt="Kick out from conversation"></i></span>
        </li>
        <li>
            <p>Tom Hanson</p>
            <span class="actions"><i class="icon-mute" alt="mute"></i> <i class="icon-forward_alt" alt="Make presenter"></i> <i class="icon-no" alt="Kick out from conversation"></i></span>
        </li>
        <li>
            <p>Mark Uraine</p>
            <span class="actions"><i class="icon-mute" alt="mute"></i> <i class="icon-forward_alt" alt="Make presenter"></i> <i class="icon-no" alt="Kick out from conversation"></i></span>
        </li>
        <li>
            <p>Some Otherguy</p>
            <span class="actions"><i class="icon-mute" alt="mute"></i> <i class="icon-forward_alt" alt="Make presenter"></i> <i class="icon-no" alt="Kick out from conversation"></i></span>
        </li>
    </ul>

2 个答案:

答案 0 :(得分:0)

你必须对每个所有.icon-mute元素进行切换并切换它的类。 代码可能就是这样。

<script>
   $(function() {
    $(".js_mute-all").click(function() {
        $(".icon-mute")each(function(){
          $(this).toggleClass('red');
        })
    });
});</script>

希望它有所帮助。

问候。

答案 1 :(得分:0)

$(".js_mute-all").click(function(e)
{
    e.preventDefault();
    $(".icon-mute").toggleClass("red");
});

我的诀窍是:http://jsfiddle.net/h6h2f/1/

通过将事件e传递给函数然后阻止默认操作(跟随锚点),原始代码可以正常工作。