答案 0 :(得分:2)
$(':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();
}
});