如何在图像的onclick事件上从追加元素中删除复选框元素后取消选中

How to uncheck checkbox element after deleting it from append element on onclick event of image?

本文关键字:元素 删除 复选框 取消 追加 图像 onclick 事件      更新时间:2023-09-26

这是我的jsfiddi想取消复选框时,从另一个div删除元素。这里我添加复选框内容到另一个div与delete链接。

function show() {
    var checkBoxes = document.getElementsByName("trainig_by_industry1");
    document.getElementById("selectBox").innerHTML = "";
    for (var i = 0; i < checkBoxes.length; i++) {
        if (checkBoxes[i].checked) {
            var da = checkBoxes[i].value;
            document.getElementById("selectBox").innerHTML += '<span class="tagRemove" >' + da + ' <img src="resources/images/Cancel-128.png" id="unc" style="height:20px; width:20px;" onclick="$(this).parent().remove(); check1();"/></span>';
        }
    }
}
function check1() {
    $('#subc1 input:checkbox').removeAttr('checked'); //$(checkBoxes[i]).attr('checked',false); }

一种解决方案是在每个checkbox中添加一个data attribute,如1,2,3…这样的:

<label for="one"><input type="checkbox" data-index="1" class="check" name="trainig_by_industry1" onchange="show()"  value="First checkbox" />First checkbox</label>
                                        ^^^^^^^^^^^^^^

然后在JS中:

将数据索引添加到您创建的对应中。

document.getElementById("selectBox").innerHTML+=  '<span class="tagRemove" data-index='+checkBoxes[i].getAttribute('data-index')+' >'+ da+ ' <img src="" alt="X" id="unc" style="height:20px; width:20px;"/></span>';
                                                                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

然后附加一个点击事件到新的span class tagRemove,而不是写一个onclick:

$(document).on('click', '.tagRemove' , function(){
  $('#subc1').find('[data-index="'+$(this).data("index")+'"]').prop('checked',false);
  $(this).remove();
})

参见提琴