请指教。 我想在容器标记复选框内添加标签,并通过单击每个标签的“x”按钮删除标签。 一切正常,除了当您单击“x”按钮并删除标签时,复选框的状态保持选中状态。 但我需要当您单击每个标签的按钮时,必须取消选中复选框的状态。
使用输入的值和名称可能更容易,但我不能使用它们 - 只能使用 id。
$(document).ready(function() {
var $list = $("#itemList");
$(".chkbox").change(function() {
var a = $('label[for="' + this.id + '"]').text();
if (this.checked) {
$list.append('<li><a href="#">'+a+'</a><button class="closebutton" value="'+a+'">X</button></li>');
}
else {
$("#itemList li:contains('"+a+"')").remove();
}
})
$(document).on('click','.closebutton',function(){
var b = this.value;
$("#itemList li:contains('"+b+"')").remove();
$('label[for="' + this.id + '"]').removeAttr('checked');
});
});
<div id="items">
<ul id="itemList">
</ul>
</div>
<div id="tab1" class="tab-pane">
<div id="ck-button"><label for="one"><input type="checkbox" id="one" class="chkbox"><span>First book</span></label> </div>
<div id="ck-button"><label for="two"><input type="checkbox" class="chkbox" id="two"><span> Second book</span></label> </div>
</div>
最佳答案
尝试
$(document).ready(function () {
var $list = $("#itemList");
$(".chkbox").change(function () {
var a = $(this).next().text();
if (this.checked) {
$('<li><a href="#">' + a + '</a><button class="closebutton" value="' + a + '">X</button></li>').appendTo($list).data('src', this);
} else {
$("#itemList li:contains('" + a + "')").remove();
}
})
$(document).on('click', '.closebutton', function () {
var $li = $(this).closest('li');
$($li.data('src')).prop('checked', false);
$li.remove();
});
});
演示:Fiddle
关于javascript - 使用关闭按钮取消选中复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20014865/