取消选中时删除复选框警报

时间:2013-11-10 14:48:32

标签: jquery checkbox alert

我有一个带有从cbox1到cbox30的唯一ID的复选框列表,我希望在用户检查特定复选框时显示不同的警报,例如,

$(document).ready(function(e) {
    $( "#cbox1" ).on( "click", function() {
        alert("Day 1 Completed Well Done!!.");
    });

    $( "#cbox2" ).on( "click", function() {
        alert("Day 2 Finished Great Job.");
    });

    $( "#cbox3" ).on( "click", function() {
        alert("That's Day 3 Done, Keep it Up!.");
    });
});

首先,是否有更简单或更具语义的方法?

其次,如果用户UNCHECKED复选框,如何删除警告框?

1 个答案:

答案 0 :(得分:3)

使用data-*属性存储消息

<input type="checkbox" id="cbox1" class="cbox" data-msg="Day 1 Completed Well Done!!." />
<input type="checkbox" id="cbox2" class="cbox" data-msg="Day 2 Finished Great Job." />
<input type="checkbox" id="cbox3" class="cbox" data-msg="That's Day 3 Done, Keep it Up!." />

然后

jQuery(function ($) {
    $(".cbox").on("click", function () {
        if (this.checked) {
            alert($(this).data('msg'));
        }
    });
});

演示:Fiddle