所有领域的明确表格字段onblur

时间:2013-12-02 16:21:14

标签: javascript forms input field onfocus

嘿所以我正在研究一个带有表格和javascript的计算器。我希望当用户单击某个字段并且值为“0”时,该字段将被清除。当他在字段外点击时值为“”我希望字段再次用0填充。我可以很容易地对这样的特定字段这样做:

document.forms[0].elements[0].onfocus = function() {
    if(this.value == "0") {
        this.value = "";
    }
};

document.forms[0].elements[0].onblur = function() {
    if(this.value == "") {
        this.value = "0";
    }
};

但是我想让它适用于每个字段,我不想为每个字段编写这一堆代码,我不想在我的html中使用内联引用。我有哪个选项?提前谢谢。

1 个答案:

答案 0 :(得分:0)

试试这个。

你也可以用'document.querySelectorAll(“form input”)'等替换'document.forms [0] .elements'。

Array.prototype.slice.call(document.forms[0].elements).forEach(function(element){
    element.onfocus = function() {
        if(this.value == "0") {
            this.value = "";
        }
    };
    element.onblur = function() {
        if(this.value == "") {
            this.value = "0";
        }
    };
})