我的表单中有一个 textarea 元素,如下所示。
<!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...";
});
当我从文本区域单击或移开鼠标时,“请在此处输入其他信息...”
不会切换(出现/消失)。
我在这个 link 中尝试了另一种方法
它有效,该方法需要函数 SetMsg
需要位于 textarea
之上。
我不喜欢这种方法,因为我想将 HTML 和 Javascript 代码分离到单独的文件中,并且因为我需要一些其他元素
<script type="text/javascript" src="advertisementlandedvalidationatclient.js"></script> below the form.
为什么它在第一个 .focus/.blur 方法中不起作用,最好的方法是什么? 谢谢
最佳答案
您可以为输入元素使用 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...');
});
关于javascript - 为什么 textarea 的 .focus() 和 .blur() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34576122/