繁体   English   中英

为什么textarea的.focus()和.blur()无法正常工作

[英]Why textarea's .focus() and .blur() don't work

我的表单中有一个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...";

});

当我单击鼠标或从文本区域中删除鼠标时, "Please enter additional information here..."不会切换(显示/消失)。

我在此链接中尝试了另一种方法,该方法有效,该方法需要功能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...');
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM