Onblur返回错误的数据

时间:2014-06-26 04:17:54

标签: javascript

我的表单检查不起作用。如果我将alias字段留空,则返回name字段为fill。

var alias = document.getElementById("alias");
var name = document.getElementById("name");
var status = '';

function checkIt() {
    if (alias.value != '') {
        document.getElementById("alias").style.borderColor = "#3c763d";
        return true;
    } else {
        document.getElementById("alias").style.borderColor = "#a94442";
        status = false;
    }
    if (name.value != '') {
        document.getElementById("name").style.borderColor = "#3c763d";
        return true;
    } else {
        document.getElementById("name").style.borderColor = "#a94442";
        status = false;
    }
}

name.onblur=checkIt;
alias.onblur=checkIt;

2 个答案:

答案 0 :(得分:1)

试试这个,你应该在事件触发时使用当前对象this而不是全局变量

var alias = document.getElementById("alias");
var name = document.getElementById("name");
var status = '';

function checkIt() {
if (this.value != '') {
    this.style.borderColor = "#3c763d";
    status = true;
} else {
    this.style.borderColor = "#a94442";
    status = false;
}
}

name.onblur=checkIt;
alias.onblur=checkIt;

JSFIDDLE DEMO

答案 1 :(得分:0)

试试这个:

Plain Js

  

脚本

var validate = function(e) {
    var v = this.value;
    this.style.borderColor = ('' !== v) ? '#3c763d' : '#a94442';
};

document.getElementById('alias').onblur = validate;
document.getElementById('name').onblur = validate;

<强> JQuery的

  

脚本

$(function(){
    $("#alias, #name").on('focusout', function() {
        var box = $(this);
        var c = ('' !== box.val()) ? '#3c763d' : '#a94442';
        box.css('border-color', c);
    });
})