javascript - 为什么 textarea 的 .focus() 和 .blur() 不起作用

标签 javascript jquery html

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

相关文章:

使用未定义作为 bool 评估的Javascript最佳实践?

javascript - 为什么Javascript扩展函数必须正确设置对象原型(prototype)构造函数?

javascript - 输入类型 ="number"在 Firefox 和 IE 中选择数字时无法删除/清除

javascript - 在 React Router v6.+ 中渲染多个元素

php - 在 php 中调用一个 javascript 函数

javascript - 在javascript中实例化新对象时设置属性值

javascript - 如何在将元素插入数组时使用三元运算符

jquery - 当鼠标下方的元素移动时,如何阻止 mousemove() 执行?

jquery - 在 jquery 中使用固定标题调整表列的大小

jquery - 检查输入字段中的数字和连字符