2016-01-03 44 views
1

我的表单中有一个textarea元素,如下所示。为什么textarea的.focus和blur不起作用

<!DOCTYPE html> 
<html> 
<head> 

</head> 
<body> 
<form id="advertiseForm" name="advertiseForm" method="post" > 
<textarea rows="20" cols="70" name="textarea" id="textarea">Please enter additional information here...</textarea> 

</form> 
<script type="text/javascript" src="advertisementlandedvalidationatclient.js"></script> 

</body> 

然后我把.focus和.blur到一个javascript文件

advertisementlandedvalidationatclient.js 

$("#textarea") 
    .focus(function() { 
     if (txt == null) return; 
     if (txt.value == "Please enter additional information here...") txt.value = ''; 

    }) 
    .blur(function() { 
     if (txt == null) return; 
     if (txt.value == '') txt.value = "Please enter additional information here..."; 

}); 

当我点击或文本区域移开鼠标,"Please enter additional information here..."不切换(出现/消失)。

我尝试另一种方法在这个link 它的工作原理,这种方法需要SetMsg必须在textarea顶部的功能。 我不喜欢这种做法,因为我想单独HTML和Javascript代码到单独的文件,并因为一些其他的元素,我需要

<script type="text/javascript" src="advertisementlandedvalidationatclient.js"></script> below the form. 

为什么不能在第一.focus工作/ .blur方法什么可能是最好的方法? 感谢

+1

什么是'txt'应该在那个代码中? – adeneo

+0

你是否包含jQuery库,因为我在你给的html示例中没有看到一个?另外为什么不使用placeholder属性,或者您是否尝试支持旧浏览器? –

回答

1

可以使用placholder属性的输入元素

<textarea rows="20" cols="70" name="textarea" id="textarea" placeholder="Please enter additional information here..."></textarea> 

如果你真的想这与jQuery做到这一点,你可以修改代码为..

$("#textarea") 
.focus(function() { 
    if ($("#textarea").val() == null) return; 
    if ($("#textarea").val() == "Please enter additional information here...") $("#textarea").val(''); 
}) 
.blur(function() { 
    if ($("#textarea").val() == null) return; 
    if ($("#textarea").val() == '') $("#textarea").val('Please enter additional information here...'); 
}); 
相关问题