添加Javascript文本水印无效

添加Javascript文本水印无效,javascript,html,Javascript,Html,我正在尝试使用javascript创建文本框水印,但使用当前代码时出现错误 网页错误详细信息 消息:“searchInput”未定义 <script type="text/javascript" language="javascript"> function watermark(inputId,text){ var inputBox = document.getElementById(searchInput); if (inputBox.value.leng

我正在尝试使用javascript创建文本框水印,但使用当前代码时出现错误

网页错误详细信息 消息:“searchInput”未定义

<script type="text/javascript" language="javascript">

function watermark(inputId,text){ 

  var inputBox = document.getElementById(searchInput); 

      if (inputBox.value.length > 0){  

           if (inputBox.value == text)  

                  inputBox.value = '';
  }   
    else   
       inputBox.value = text;
 }
</script>

<input name="keyword2" id="searchInput" type="text" class="searchbox2"
       value="Enter a State, County, City or Zip" size="77" maxlength="30"
       onfocus="watermark('searchInput','Enter a State, County, City or Zip');"
       onblur="watermark('searchInput','Enter a State, County, City or Zip');"/>

函数水印(输入,文本){
var inputBox=document.getElementById(searchInput);
如果(inputBox.value.length>0){
如果(inputBox.value==文本)
inputBox.value='';
}   
其他的
inputBox.value=文本;
}

在searchInput周围添加引号

getElementById接受一个字符串,您正在引用一个未声明的变量

document.getElementById('searchInput'); 

函数所需的变量名为
inputId
而不是
searchInput

所以改变这条线

var inputBox = document.getElementById(searchInput); 


备选方案

为了避免完全命名元素,只需将
this
作为第一个参数传递,因为它将引用元素

function watermark(element, text) {
    if (element.value.length > 0) {
        if (element.value == text) {
            element.value = '';
        }
    }
    else element.value = text;
}



演示在

您需要在搜索输入getElementById声明周围加引号,如下所示:

document.getElementById('searchInput')

此外,一种更直接、更简单的方法是将其输入到您的输入中:

onfocus=“如果(this.value==this.defaultValue)this.value=”
onblur=“如果(this.value='')this.value=this.defaultValue;”


希望这有帮助:)

谢谢,我忘了!你很高兴知道如何将输入中的文本样式设置为灰色吗?当然,如果所有浏览器都支持html5占位符属性,那么只需在css
#searchInput{color:#666}
中添加这个就好了
function watermark(element, text) {
    if (element.value.length > 0) {
        if (element.value == text) {
            element.value = '';
        }
    }
    else element.value = text;
}
<input name="keyword2" id="searchInput" type="text" class="searchbox2"
       value="Enter a State, County, City or Zip" size="77" maxlength="30"
       onfocus="watermark(this,'Enter a State, County, City or Zip');"
       onblur="watermark(this,'Enter a State, County, City or Zip');"/>