0

我想在 jquery 中创建一个 if / else 语句,并弹出一个警报框,并根据我选择的 div 的背景颜色应该改变什么。

IE)

我有一个状态灯,当我按下它时,我会收到一个警报,如果我按下 OK,它会改变颜色,如果我按下 Cancel,颜色不会改变。

我怎么做?

提前致谢。

这就是代码现在的样子,

HTML

<div id="checklistItem">
    <div class="status1">
        <p class="item1"> Sample item </p> 
    </div>
    <div class="itemInfo1"></div>
</div>

CSS

.status1{
height:15px;
width:15px;
border-radius:15px;
background:red;
position:relative;
top:20px;
left:10px;
cursor:pointer;
}

jQuery

$(document).ready(function() {
$('.status1').click(function(e) {
    e.preventDefault();
    if (window.confirm("Are you sure?")) {
    }
    });
}); 
4

1 回答 1

1

首先,欢迎(返回)StackOverflow,感谢您在问题中编辑更多细节!

解决方案非常简单。if对话框周围的语句决定window.confirm了用户选择的内容。如果结果是true,用户选择“Ok”,否则用户选择“Cancel”。您可以在Mozilla 开发者网络上阅读更多相关信息。

由此我们可以相应地改变背景:

$('.status1').click(function(e) {
    e.preventDefault();

    /* Hold $(this) in a variable to prevent having to recall it.
     * Here $this is equal to the element which has been clicked on.
     */
    var $this = $(this);

    if (window.confirm("Are you sure?")) {
        /* If the user selected "Ok", change the background to green. */
        $this.css({backgroundColor: '#0f0'});
    }
    else {
        /* Otherwise the user selected "Cancel", change the background to red. */
        $this.css({backgroundColor: '#f00'});
    }
});

更好的解决方案是简单地引入一个新的 CSS 类:

.confirmed {
    background: #0f0; /* Green background. */
}

然后使用jQuery 的toggleClass()方法根据用户选择 Ok 还是 Cancel 来添加或删除类:

$this.toggleClass('confirmed', window.confirm("Are you sure?"));

toggleClass()方法接受一个布尔值(truefalse)作为它的第二个参数,我们通过我们的window.confirm(). 'confirmed'是我们要添加或删除的类的名称。

JSFiddle 演示

于 2013-10-23T11:22:55.730 回答