选中复选框时,如果在复选框旁边添加新的div标签,并且当选中两个复选框时,必须显示两个div标签。请帮助并让我使用jquery

来解决这个模块
有帮助吗?

解决方案

$(':checkbox').click(function () {
    if ($(this).attr('checked')) {
        // create new div
        var newDiv = $('<div>contents</div>');

        // you can insert element like this:
        newDiv.insertAfter($(this));

        // or like that (choose syntax that you prefer):
        $(this).after(newDiv);
    } else {
        // this will remove div next to current element if it's present
        $(this).next().filter('div').remove();
    }
});

如果你不想在复选框'标签旁边添加这个新的div,那么首先要确保你的复选框设置了id,并使用标签中的属性连接标签和复选框:

<label for="myCb1">test</label>
<input type="checkbox" id="myCb1" value="1" />

现在你可以稍微修改一下JS代码,你就完成了:

$(':checkbox').click(function () {
    // current checkbox id
    var id = $(this).attr('id');

    // checkbox' label
    var label = $('label[for=' + id + ']');

    if ($(this).attr('checked')) {
        // create new div
        var newDiv = $('<div>contents</div>');

        // insert div element
        newDiv.insertAfter(label);
    } else {
        // this will remove div next to current element if it's present
        label.next().filter('div').remove();
    }
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top