[英]select and unselect not working for dynamically created checkbox in js
我已經使用Bootstrap JS和CSS在Java腳本復選框樹中動態創建了。 選擇和取消選擇無效: 在此處輸入圖片描述
在第二張圖片中是從js動態創建的html: 在此處輸入圖片描述如果我將其復制並在html中創建,則它可以正常工作。 如何動態創建復選框樹?
$(function() { $('input[type="checkbox"]').change(checkboxChanged); function checkboxChanged() { var $this = $(this), checked = $this.prop("checked"), container = $this.parent(), siblings = container.siblings(); container.find('input[type="checkbox"]') .prop({ indeterminate: false, checked: checked }) .siblings('label') .removeClass('custom-checked custom-unchecked custom-indeterminate') .addClass(checked ? 'custom-checked' : 'custom-unchecked'); checkSiblings(container, checked); } function checkSiblings($el, checked) { var parent = $el.parent().parent(), all = true, indeterminate = false; $el.siblings().each(function() { return all = ($(this).children('input[type="checkbox"]').prop("checked") === checked); }); if (all && checked) { parent.children('input[type="checkbox"]') .prop({ indeterminate: false, checked: checked }) .siblings('label') .removeClass('custom-checked custom-unchecked custom-indeterminate') .addClass(checked ? 'custom-checked' : 'custom-unchecked'); checkSiblings(parent, checked); } else if (all && !checked) { indeterminate = parent.find('input[type="checkbox"]:checked').length > 0; parent.children('input[type="checkbox"]') .prop("checked", checked) .prop("indeterminate", indeterminate) .siblings('label') .removeClass('custom-checked custom-unchecked custom-indeterminate') .addClass(indeterminate ? 'custom-indeterminate' : (checked ? 'custom-checked' : 'custom-unchecked')); checkSiblings(parent, checked); } else { $el.parents("li").children('input[type="checkbox"]') .prop({ indeterminate: true, checked: false }) .siblings('label') .removeClass('custom-checked custom-unchecked custom-indeterminate') .addClass('custom-indeterminate'); } } });
* { margin: 0; padding: 0; } #page-wrap { margin: auto 0; } .treeview { margin: 10px 0 0 20px; } ul { list-style: none; } .treeview li { background: url(http://jquery.bassistance.de/treeview/images/treeview-default-line.gif) 0 0 no-repeat; padding: 2px 0 2px 16px; } .treeview > li:first-child > label { /* style for the root element - IE8 supports :first-child but not :last-child ..... */ } .treeview li.last { background-position: 0 -1766px; } .treeview li > input { height: 16px; width: 16px; /* hide the inputs but keep them in the layout with events (use opacity) */ opacity: 0; filter: alpha(opacity=0); /* internet explorer */ -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=0)"; /*IE8*/ } .treeview li > label { background: url(https://www.thecssninja.com/demo/css_custom-forms/gr_custom-inputs.png) 0 -1px no-repeat; /* move left to cover the original checkbox area */ margin-left: -20px; /* pad the text to make room for image */ padding-left: 20px; } /* Unchecked styles */ .treeview .custom-unchecked { background-position: 0 -1px; } .treeview .custom-unchecked:hover { background-position: 0 -21px; } /* Checked styles */ .treeview .custom-checked { background-position: 0 -81px; } .treeview .custom-checked:hover { background-position: 0 -101px; } /* Indeterminate styles */ .treeview .custom-indeterminate { background-position: 0 -141px; } .treeview .custom-indeterminate:hover { background-position: 0 -121px; }
<body class="skin-blue sidebar-mini" style="height: auto; min-height: 100%;"> <!-- changing values in row --> <input id="rowNumber" class="form-control " type="hidden"> <div class="wrapper" style="height: auto; min-height: 100%; background-color: #ECEFF4;"> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-xs-12"> <!-- /.box --> <div class="box"> <!-- /.box-header --> <div class="box-body"> <button onclick="addCheckBox()">add</button> <input id="check" name="checkBoxes"> <div id="page-wrap"> <ul class="treeview"> <li> <input type="checkbox" name="short" id="short"> <label for="short" class="custom-unchecked">Short Things</label> <ul id="cc"> </ul> </li> </ul> </div> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <!-- /.col --> </div> <!-- /.row --> </section> <!-- /.content --> </div> <script src="//code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=" crossorigin="anonymous"></script> <script type="text/javascript"> function addCheckBox() { var listElement = document.getElementById('cc'); var check_value = new Array(); check_value[1] = "Yellow"; check_value[2] = "Red"; check_value[3] = "Green"; var li, checkbox, label, br, a; var title = document.getElementById('check').value; for (var i = 1; i <= title; i++) { li = document.createElement("li"); if (i == title) { li.className = "last"; } checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.name = "short-" + i; checkbox.id = "short-" + i; label = document.createElement("label"); label.htmlFor = "short-" + i; label.className = "custom-unchecked"; label.setAttribute("class", "custom-unchecked"); label.innerHTML = check_value[i]; li.innerHTML += checkbox.outerHTML + label.outerHTML; listElement.appendChild(li); /*li.appendChild(checkbox); //li.appendChild(label); listElement.appendChild(li); listElement.appendChild(checkbox); listElement.appendChild(label); */ } } </script> </body>
從代碼的角度來看,所有這些都可以正常工作。
用幾句話在創建新元素后在addCheckBox()
函數中應該添加:
$('input[type="checkbox"]').off('change'); // detach event
$('input[type="checkbox"]').on('change', checkboxChanged); // add new event
正如@ Alx-lark所說,您遇到的問題是您在初始頁面加載時綁定更改事件,但是事件綁定的工作方式是, 以后添加到頁面的任何后續復選框元素都不會被綁定。 他的答案中提到的解決方案-在所有復選框上解除綁定,然后在所有復選框(包括最近添加的復選框)上重新綁定,應該可以工作。
您還可以在添加單個復選框時對其進行綁定,或者可以在始終存在的元素(如document
上更高的位置進行綁定
這可能是最簡單的更改,更改行
$('input[type="checkbox"]').change(checkboxChanged)
到$(document).on('change', 'input[type="checkbox"]', checkboxChanged);
這稱為事件委托 ,您可以在這里閱讀有關信息: https : //learn.jquery.com/events/event-delegation/
通過事件委托,我們可以將單個事件偵聽器附加到父元素,該元素將為與選擇器匹配的所有后代觸發,無論這些后代現在存在還是將來添加。
function checkboxChanged() { var $this = $(this), checked = $this.prop("checked"), container = $this.parent(), siblings = container.siblings(); container.find('input[type="checkbox"]') .prop({ indeterminate: false, checked: checked }) .siblings('label') .removeClass('custom-checked custom-unchecked custom-indeterminate') .addClass(checked ? 'custom-checked' : 'custom-unchecked'); checkSiblings(container, checked); } function checkSiblings($el, checked) { var parent = $el.parent().parent(), all = true, indeterminate = false; $el.siblings().each(function() { return all = ($(this).children('input[type="checkbox"]').prop("checked") === checked); }); if (all && checked) { parent.children('input[type="checkbox"]') .prop({ indeterminate: false, checked: checked }) .siblings('label') .removeClass('custom-checked custom-unchecked custom-indeterminate') .addClass(checked ? 'custom-checked' : 'custom-unchecked'); checkSiblings(parent, checked); } else if (all && !checked) { indeterminate = parent.find('input[type="checkbox"]:checked').length > 0; parent.children('input[type="checkbox"]') .prop("checked", checked) .prop("indeterminate", indeterminate) .siblings('label') .removeClass('custom-checked custom-unchecked custom-indeterminate') .addClass(indeterminate ? 'custom-indeterminate' : (checked ? 'custom-checked' : 'custom-unchecked')); checkSiblings(parent, checked); } else { $el.parents("li").children('input[type="checkbox"]') .prop({ indeterminate: true, checked: false }) .siblings('label') .removeClass('custom-checked custom-unchecked custom-indeterminate') .addClass('custom-indeterminate'); } } $(function() { $(document).on('change', 'input[type="checkbox"]', checkboxChanged); });
* { margin: 0; padding: 0; } #page-wrap { margin: auto 0; } .treeview { margin: 10px 0 0 20px; } ul { list-style: none; } .treeview li { background: url(http://jquery.bassistance.de/treeview/images/treeview-default-line.gif) 0 0 no-repeat; padding: 2px 0 2px 16px; } .treeview > li:first-child > label { /* style for the root element - IE8 supports :first-child but not :last-child ..... */ } .treeview li.last { background-position: 0 -1766px; } .treeview li > input { height: 16px; width: 16px; /* hide the inputs but keep them in the layout with events (use opacity) */ opacity: 0; filter: alpha(opacity=0); /* internet explorer */ -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=0)"; /*IE8*/ } .treeview li > label { background: url(https://www.thecssninja.com/demo/css_custom-forms/gr_custom-inputs.png) 0 -1px no-repeat; /* move left to cover the original checkbox area */ margin-left: -20px; /* pad the text to make room for image */ padding-left: 20px; } /* Unchecked styles */ .treeview .custom-unchecked { background-position: 0 -1px; } .treeview .custom-unchecked:hover { background-position: 0 -21px; } /* Checked styles */ .treeview .custom-checked { background-position: 0 -81px; } .treeview .custom-checked:hover { background-position: 0 -101px; } /* Indeterminate styles */ .treeview .custom-indeterminate { background-position: 0 -141px; } .treeview .custom-indeterminate:hover { background-position: 0 -121px; }
<body class="skin-blue sidebar-mini" style="height: auto; min-height: 100%;"> <!-- changing values in row --> <input id="rowNumber" class="form-control " type="hidden"> <div class="wrapper" style="height: auto; min-height: 100%; background-color: #ECEFF4;"> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-xs-12"> <!-- /.box --> <div class="box"> <!-- /.box-header --> <div class="box-body"> <button onclick="addCheckBox()">add</button> <input id="check" name="checkBoxes"> <div id="page-wrap"> <ul class="treeview"> <li> <input type="checkbox" name="short" id="short"> <label for="short" class="custom-unchecked">Short Things</label> <ul id="cc"> </ul> </li> </ul> </div> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <!-- /.col --> </div> <!-- /.row --> </section> <!-- /.content --> </div> <script src="//code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=" crossorigin="anonymous"></script> <script type="text/javascript"> function addCheckBox() { var listElement = document.getElementById('cc'); var check_value = new Array(); check_value[1] = "Yellow"; check_value[2] = "Red"; check_value[3] = "Green"; var li, checkbox, label, br, a; var title = document.getElementById('check').value; for (var i = 1; i <= title; i++) { li = document.createElement("li"); if (i == title) { li.className = "last"; } checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.name = "short-" + i; checkbox.id = "short-" + i; label = document.createElement("label"); label.htmlFor = "short-" + i; label.className = "custom-unchecked"; label.setAttribute("class", "custom-unchecked"); label.innerHTML = check_value[i]; li.innerHTML += checkbox.outerHTML + label.outerHTML; listElement.appendChild(li); /*li.appendChild(checkbox); //li.appendChild(label); listElement.appendChild(li); listElement.appendChild(checkbox); listElement.appendChild(label); */ } } </script> </body>
對我來說,我必須在文件之后瞄准容器
$(document).on('change', '.input-container input[class^=open-all]', function(e) {
//console.log(e);
if (e.target !== this)
return;
if ($(this).is(':checked')) {
//true
switchStatus = $(this).is(':checked');
}
else {
// flase
switchStatus = $(this).is(':checked');
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.