Javascript值比较不合逻辑

Javascript值比较不合逻辑,javascript,html,css,Javascript,Html,Css,首先是守则: 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 ==

首先是守则:

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(thefield.value==“”| | thefield.value==null)放进去,它可以工作,但你必须有一个空格。如果盒子是空的,它就不能工作。这只影响文本区域。它可以很好地处理空白文本框


我真的被它弄糊涂了,有人知道为什么空格可以工作,而空的“”或“”或null不能工作吗?

什么不工作?这适用于空的
'

建议:

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

也许值得将您的代码倒置并像这样进行测试:

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

和往常一样,这不是javascript的问题,而是代码的问题。可能在问题中发布的部分之外您应该使用jsfiddle.net来显示一个示例,并且您可能希望尝试使用
.text
而不是value。这是因为您的TEXTAREA元素可能包含一些空格字符。我建议这样做:
if(thefield.value.trim()=='')
(请注意,
trim()
在IE8中没有实现,所以您必须手动处理)。如果有人遇到这个问题,我有一些其他javascript干扰了这个样式。几乎找不到。谢谢你们的帮助。