簡體   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