0

我有一个具有从 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!.");
    });
});

首先,是否有一种更简单或更语义化的方式来做到这一点?

其次,如果用户取消选中复选框,我该如何删除警报框?

4

1 回答 1

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'));
        }
    });
});

演示:小提琴

于 2013-11-10T14:54:05.960 回答