Javascript值比较是不合逻辑的

Javascript value comparison is illogical

本文关键字:不合逻辑 比较 Javascript      更新时间:2023-09-26

首先代码:

function focusAction(thefield, autofill) {
if (thefield.value == thefield.defaultValue && (thefield.style.color == 'rgb(153, 153, 153)' || thefield.style.color == '#999999')) {
    thefield.style.color = "#000000";
    if (autofill == "")
    thefield.value = '';
}
}
function blurAction(thefield, autofill) {
    //var content = thefield.value;
if (thefield.value == '' || thefield.value == null) {
    thefield.value = thefield.defaultValue;
    if (autofill == "")
        thefield.style.color = "#999999";
} else {
    //thefield.style.color="green";
}
}

那么事情是这样的:如果我把If(字段)。Value == " " ||该字段。值== null),但必须有一个空格。如果盒子是空的,它就不能工作。这只影响文本区域。它适用于空白文本框。

我真的很困惑,有人知道为什么一个空间工作,但一个空的"或"或null不?

什么不行?这适用于空'': http://jsfiddle.net/wYPNX/

建议:

  • 使用类进行视觉更改。 CSS比JavaScript更容易修改,而且更健壮。
  • 我建议使用更健壮的表单插件。如果不希望这样,也没关系。我只是建议使用插件,因为有更多的支持,通常有更少的bug比自己创建的项目。
  • 修剪输入。这意味着前导和尾随空格被忽略,让您更好地了解实际存在的内容。这可能会解决你的问题,除非它是由于下一点。
  • 你的意思是与空白空间比较吗?通常你想知道它是空的还是空的,而不是它是否有一个空格或null。
  • 使用===与null比较。

也许这是值得的反转你的代码和测试像这样:

if (thefield.value && thefield.value.length > 0) {
    //thefield.style.color="green";
} 
else {
    thefield.value = thefield.defaultValue;
    if (autofill == "")
        thefield.style.color = "#999999";
}