在点击事件时使用jQuery在类之间交替

And*_*y89 8 javascript css jquery addclass removeclass

我在这里感觉非常愚蠢 - 我无法在jQuery中使用简单的类切换语句!我只能坐在最后45分钟的挫折中,我搜索了Stack Overflow的问题和答案,但无济于事.

My goal is, upon clicking an item with the colorClick id (already containing a default class of "white"), to rotate that item between being assigned the class green, yellow, orange, red, and back to white again (ad infinitum).

The CSS is simple - each class simply corresponds to a different background color.

The HTML is simple - a div tag with two CSS classes (one static, one to be changed by jQuery).

The jQuery is simple - read the class on the clicked item, and change it.

And now, you understand what vexes me. Here's what I'm working with so far:

$("#colorClick").click(function () {
    if ($(this).hasClass('white')) {
        $(this).removeClass("white").addClass("green");
    } else if ($(this).hasClass('green')) {
        $(this).removeClass('green').addClass('yellow');
    } else if ($(this).hasClass('yellow')) {
        $(this).removeClass('yellow').addClass('orange');
    } else if ($(this).hasClass('orange')) {
        $(this).removeClass('orange').addClass('red');
    } else if ($(this).hasClass('red')) {
        $(this).removeClass('red').addClass('white');
});
Run Code Online (Sandbox Code Playgroud)
.toDoItem {
    text-align: left;
    padding: 3px;
    margin-bottom: 5px;
    border: 1px solid;
    border-color: #e8e7e7;
}
.white {
    background-color: #ffffff;
}
.green {
    background-color: #b2d8b2;
}
.yellow {
    background-color: #ffffb2;
}
.orange {
    background-color: #ffe4b2;
}
.red {
    background-color: #ffb2b2;
}
Run Code Online (Sandbox Code Playgroud)
<div class="toDoItem white" id="colorClick">To-do list item</div>
<div class="toDoItem white" id="colorClick">To-do list item</div>
<div class="toDoItem white" id="colorClick">To-do list item</div>
Run Code Online (Sandbox Code Playgroud)

Link to the fiddle: http://jsfiddle.net/andrewcbailey89/4Lbm99v0/2/

小智 30

首先,在制作列表时,您应该使用正确的列表元素.您的"待办事项"列表符合描述列表(<dl>)的定义,因此您应该使用该列表而不是<div>元素.

您可以通过删除类并创建颜色数组来保存大量代码行.确保颜色与您希望它们显示的顺序相同.我们将使用此数组根据递增的计数器设置背景颜色.

var colors = ['#b2d8b2', '#ffffb2', '#ffe4b2', '#ffb2b2', '#fff'];
Run Code Online (Sandbox Code Playgroud)

您还可以通过使用"工厂"函数来大大简化脚本,该函数定义范围并构建它返回的事件侦听器函数.这为每个侦听器函数创建了一个"安全"范围,我们可以定义将在事件之间存储信息的变量.

在下面的代码片段中,我们定义了一个count我们在每次点击时递增的变量.当使用模运算符除以颜色数组的长度时,我们使用递增的变量余数%.如果数字小于数组的长度,它将返回数字,否则当除以数组的长度时它将返回余数,允许我们连续循环.

function todoItemListener() {
    var count = 0;
    return function () {
        $(this).css({ 'background-color': colors[count++ % colors.length] });
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我们不是正常地指定函数声明(没有括号),而是分配工厂函数的结果,只需附加括号,函数将执行并返回结果的监听器函数.这允许我们添加任意数量的侦听器函数,因此如果您要添加新的待办事项列表项,我们可以简单地构建另一个侦听器函数.

$('.todo-list dd').each(function () {
    $(this).on('click', todoItemListener());
});

$('.add-item').on('click', function () {
    var list = this.parentNode.parentNode;
    $('<dd>To-do list item</dd>').appendTo(list).on('click', todoItemListener());
});
Run Code Online (Sandbox Code Playgroud)

此方法还允许您随意轻松更改颜色数组.因此,如果在页面上的某个位置选择了某个选项,则可以使用另一种颜色,或者不可用.

此外,对于一些额外的UX优点,我添加了CSS以停止在单击时选择文本(这可能会令人讨厌)并将光标更改为指针以使其具有更可操作的感觉.


这是完整的演示,我已经包含多个待办事项列表,以表明它可以完成.

var colors = ['#b2d8b2', '#ffffb2', '#ffe4b2', '#ffb2b2', '#fff'];

function todoItemListener() {
    var count = 0;
    return function () {
        $(this).css({ 'background-color': colors[count++ % colors.length] });
    }
}

$('.todo-list dd').each(function () {
    $(this).on('click', todoItemListener());
});

$('.add-item').on('click', function () {
    var list = this.parentNode.parentNode;
    $('<dd>To-do list item</dd>').appendTo(list).on('click', todoItemListener());
});
Run Code Online (Sandbox Code Playgroud)
.glyphicon-plus-sign {
    font-size: 15px;
}
.todo-list {
    background: #efefef;
    padding: 3px;
}
.todo-list dd {
    margin: 0;
    text-align: left;
    padding: 3px;
    margin-bottom: 7px;
    border: 1px solid;
    border-color: #e8e7e7;
    background-color: #fff;
}
.add-item, .todo-list dd {
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
    user-select: none;
    cursor: pointer;
}
.add-item {
    float: right;
    margin: 4px;
}
.todo-list dh::after {
    content: "";
    display: block;
    clear: both;
}
.todo-list dh h3 {
    float: left;
    margin: 0px;
    max-width: 100%;
    overflow: hidden;
}

/* This rule is for the demo only */
.wrp {
    float: left;
    width: 33.33333333%;
    padding: 1px;
}
Run Code Online (Sandbox Code Playgroud)
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<div class="wrp">

    <dl class="todo-list" id="todo-list-1">
        <dh>
            <h3 class="center" contenteditable>To Do List 1</h3>
            <span class="add-item glyphicon glyphicon-plus-sign"></span>
        </dh>
        <dd>To-do list item</dd>
        <dd>To-do list item</dd>
        <dd>To-do list item</dd>
    </dl>
    
</div>
<div class="wrp">

    <dl class="todo-list" id="todo-list-2">
        <dh>
            <h3 class="center">To Do List 2</h3>
            <span class="add-item glyphicon glyphicon-plus-sign"></span>
        </dh>
        <dd>To-do list item</dd>
        <dd>To-do list item</dd>
        <dd>To-do list item</dd>
    </dl>
    
</div>
<div class="wrp">

    <dl class="todo-list" id="todo-list-3">
        <dh>
            <h3 class="center">To Do List 3</h3>
            <span class="add-item glyphicon glyphicon-plus-sign"></span>
        </dh>
        <dd>To-do list item</dd>
        <dd>To-do list item</dd>
        <dd>To-do list item</dd>
    </dl>
    
</div>
Run Code Online (Sandbox Code Playgroud)


And*_*oke 8

You are missing some quotes in a few places, and you didn't close the last if statement.

ex: $(this).hasClass(green) should be $(this).hasClass('green')

Additionally, you should change colorClick to a class rather than an ID, as there are multiple of these elements.

I also changed all of your quotes to single quotes for consistency's sake.

Here is a working snippet:

$(".colorClick").click(function () {
    if ($(this).hasClass('white')) {
        $(this).removeClass('white').addClass('green');
    } else if ($(this).hasClass('green')) {
        $(this).removeClass('green').addClass('yellow');
    } else if ($(this).hasClass('yellow')) {
        $(this).removeClass('yellow').addClass('orange');
    } else if ($(this).hasClass('orange')) {
        $(this).removeClass('orange').addClass('red');
    } else if ($(this).hasClass('red')) {
        $(this).removeClass('red').addClass('white');    
    }
});
Run Code Online (Sandbox Code Playgroud)
.toDoItem {
    text-align: left;
    padding: 3px;
    margin-bottom: 5px;
    border: 1px solid;
    border-color: #e8e7e7;
}
.white {
    background-color: #ffffff;
}
.green {
    background-color: #b2d8b2;
}
.yellow {
    background-color: #ffffb2;
}
.orange {
    background-color: #ffe4b2;
}
.red {
    background-color: #ffb2b2;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="colorClick toDoItem white">To-do list item</div>
<div class="colorClick toDoItem white">To-do list item</div>
<div class="colorClick toDoItem white">To-do list item</div>
Run Code Online (Sandbox Code Playgroud)