javascript - 树中的递归错误太多

标签 javascript jquery

您好 stackoverflow 社区。我需要有关“递归过多”错误的帮助。当我执行这些功能时,它出现了,很奇怪,但一切正常,只是出现错误。:

function check_checker (siblings, status) {
    if (siblings) {
        if (status == true) {
            $(siblings).children('li.imCheckbox').children('input').prop( "checked", true );
            if ($(siblings).children('ul')) {
                check_checker($(siblings).children('ul'), true);
            }                                           
        } else {
            $(siblings).children('li.imCheckbox').children('input').prop( "checked", false );
            if ($(siblings).children('ul')) {
                check_checker($(siblings).children('ul'), false);
            }                                           
        }
    }
}
$(document).ready(function(){
    $('body').on('click', 'input[name=impTaskCh]', function(){
        if ($(this).is(':checked')) {
            var siblingas = $(this).parent().siblings('ul');
            check_checker(siblingas, true);
        } else {
            var siblingas = $(this).parent().siblings('ul');
            check_checker(siblingas, false);
        }
    });
});

单击“检查”时,如果 ul 有 ul,则会检查所有复选框。也许 check_checker 永远不会结束还是什么?大家觉得呢?

最佳答案

是的,这永无止境。 $(siblings).children('ul') 将返回一个 Object,它是 true,所以它永远是 true。我建议改用 length 属性。

function check_checker (siblings, status) {
    if (siblings) {
        if (status == true) {
            $(siblings).children('li.imCheckbox').children('input').prop( "checked", true );
            if ($(siblings).children('ul').length > 0) {
                check_checker($(siblings).children('ul'), true);
            }                                           
        } else {
            $(siblings).children('li.imCheckbox').children('input').prop( "checked", false );
            if ($(siblings).children('ul').length > 0) {
                check_checker($(siblings).children('ul'), false);
            }                                           
        }
    }
}

关于javascript - 树中的递归错误太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36474995/

相关文章:

javascript - 根据Ajax返回的数据提交表单

javascript - 从外部 div 单击时的 Jquery 和 Javascript 滚动图像

javascript - 使用高级自定义字段插件和转发器字段在 Wordpress 中制作幻灯片

javascript - 为什么 MS Ajax 在创建对象方法时使用命名 JS 函数?

jquery 创建 Spans,然后对其应用函数

javascript - 在页面向下滚动后加载 iframe

javascript - 尝试使用 jQuery.ajax 发送 FormData 时出错

javascript - 通过值比较合并 JSON 对象

javascript - jQuery: "refresh"事件处理程序的任何方式?

javascript - 如何摆脱 React 应用程序中的 "Functions are not valid as a React child"警告