我有一个 WooCommerce 在线商店,我正在尝试让用户正确选择类别。
这个想法是,如果他们选择一个子类别,那么父类别也会被选择。
我已经这样做了,但是当取消选中类别子项(并且没有检查输入)时,父级仍保持选中状态。
$('ul.product_cat_list').find('input[type=checkbox]').each(function(index, input) {
$(input).bind('change', function() {
var checkbox = $(this);
var is_checked = $(checkbox).is(':checked');
if(is_checked) {
$(checkbox).parents('li').children('input').attr('checked', 'checked');
} else {
$(checkbox).parentsUntil('ul').find('input').removeAttr('checked');
}
});
});
Run Code Online (Sandbox Code Playgroud)
这里是小提琴
查看您的标记,以下是层次结构:
\n\nproduct_cat_list\n li\n input+ul.children\n li\n input+ul.children\n li\n li\n li\n input+ul.children\n li\n li\n input+ul.children\n li\n li\n input+ul.children\n li\n li\n li\n input+ul.children\n li\n input\n li\n input\n li\n input\n li\n input\n li\n li\n input+ul.children\n li\n li\n li\n li\n li\n li\n\n li \nRun Code Online (Sandbox Code Playgroud)\n\n我添加了更多级别以便运行测试。\n运行测试后可以看到,从起点开始重复执行相同的操作。因此,您将需要一个递归调用的函数。
\n\nproduct_cat_list\n li\n input+ul.children\n li\n input+ul.children\n li\n li\n li\n input+ul.children\n li\n li\n input+ul.children\n li\n li\n input+ul.children\n li\n li\n li\n input+ul.children\n li\n input\n li\n input\n li\n input\n li\n input\n li\n li\n input+ul.children\n li\n li\n li\n li\n li\n li\n\n li \nRun Code Online (Sandbox Code Playgroud)\r\n $(document).ready(function() {\r\n $("ul.product_cat_list input[type=checkbox]").on("change", function() {\r\n\r\n var checkboxValue = $(this).prop("checked");\r\n\r\n //call the recursive function for the first time\r\n decideParentsValue($(this));\r\n\r\n //Compulsorily apply check value Down in DOM\r\n $(this).closest("li").find(".children input[type=checkbox]").prop("checked", checkboxValue);\r\n\r\n\r\n });\r\n\r\n //the recursive function \r\n function decideParentsValue(me) {\r\n var shouldTraverseUp = false;\r\n var checkedCount = 0;\r\n var myValue = me.prop("checked");\r\n\r\n //inspect my siblings to decide parents value\r\n $.each($(me).closest(".children").children(\'li\'), function() {\r\n var checkbox = $(this).children("input[type=checkbox]");\r\n if ($(checkbox).prop("checked")) {\r\n checkedCount = checkedCount + 1;\r\n }\r\n });\r\n\r\n //if I am checked and my siblings are also checked do nothing\r\n //OR\r\n //if I am unchecked and my any sibling is checked do nothing\r\n if ((myValue == true && checkedCount == 1) || (myValue == false && checkedCount == 0)) {\r\n shouldTraverseUp = true;\r\n }\r\n if (shouldTraverseUp == true) {\r\n var inputCheckBox = $(me).closest(".children").siblings("input[type=checkbox]");\r\n inputCheckBox.prop("checked", me.prop("checked"));\r\n decideParentsValue(inputCheckBox);\r\n }\r\n\r\n }\r\n });Run Code Online (Sandbox Code Playgroud)\r\n我希望这可以帮助你!
\n| 归档时间: |
|
| 查看次数: |
2906 次 |
| 最近记录: |