• 设置表单的默认值、检测表单是否变更


    通过动态加载表单内容,要求检测加载之后有没有变更过,可以通过defaultValue或者defaultSelected、defaultChecked属性来完成


    首先,加载完成后设置默认值为当前状态的值:

    //设置当前值为表单默认值
    function setDefault(element) {
        if (typeof (element) == "string") {
            element = document.getElementById(element);
            if (!element) { return null; }
        }
        var type = element.type;
        if (type == "checkbox" || type == "radio") {
            element.defaultChecked = element.checked;
        }
        else if (type == "hidden" || type == "password" || type == "text" || type == "textarea") {
            element.defaultValue = element.value;
        }
        else if (type == "select-one" || type == "select-multiple") {
            for (var j = 0; j < element.options.length; j++) {
                element.options[j].defaultSelected = element.options[j].selected;
            }
        }
        var childs = element.childNodes;
        for (var i = 0; i < childs.length; i++) {
            setDefault(childs[i]);
        }
    }


    检测代码:

    //判断表单是否改变过
    function formIsDirty(form) {
        if (typeof (form) == "string") {
            form = document.getElementById(form);
            if (!form) { return null;}
        }
        for (var i = 0; i < form.elements.length; i++) {
            var element = form.elements[i];
            var type = element.type;
            if (type == "checkbox" || type == "radio") {
                if (element.checked != element.defaultChecked) {
                    return true;
                }
            }
            else if (type == "hidden" || type == "password" || type == "text" || type == "textarea") {
                if (element.value != element.defaultValue) {
                    return true;
                }
            }
            else if (type == "select-one" || type == "select-multiple") {
                for (var j = 0; j < element.options.length; j++) {
                    if (element.options[j].selected != element.options[j].defaultSelected) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


  • 相关阅读:
    闭包跟装饰器
    几个常见的面试题目
    函数的进阶
    python的生成器和迭代器
    Python的数据类型
    “随手记”开发记录day09
    “随手记”开发记录day08
    “随手记”开发记录day07
    “随手记”开发记录day06
    “随手记”开发记录day05
  • 原文地址:https://www.cnblogs.com/apollokk/p/6713831.html
Copyright © 2020-2023  润新知