【发布时间】:2009-07-30 05:28:54
【问题描述】:
如何在选中复选框时添加新的 div 标签 在复选框旁边以及选中两个复选框时必须显示两个 div 标签。请帮助并让我使用 jquery 解决这个模块
【问题讨论】:
标签: jquery html checkbox add checked
如何在选中复选框时添加新的 div 标签 在复选框旁边以及选中两个复选框时必须显示两个 div 标签。请帮助并让我使用 jquery 解决这个模块
【问题讨论】:
标签: jquery html checkbox add checked
$(':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,并使用标签中的 for 属性将标签与复选框连接起来:
<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();
}
});
【讨论】: