为什么textArea不更新

Why does textArea not update?

本文关键字:更新 textArea 为什么      更新时间:2023-09-26

我已经检查了一个警报,我的值是"输入你的评论…",但我的if语句返回false。

谢谢。

function ClearText(e) {
  //alert(document.getElementById('contactMe').value);
  if (document.getElementById('contactMe').value == 'Enter your comment...') {
    document.getElementById('contactMe').value = "";
  }
}
var x = document.getElementById('contactMe');
x.addEventListener('click', ClearText, false);
<html>
<body>
  <textarea id=contactMe rows=4 cols=40>Enter your comment...</textarea>
  <script src="contactBox.js">
  </script>
</body>
</html>

我知道你想要完成什么,你可以通过使用html属性占位符来避免javascript。

考虑以下代码:

<html>
<body>
  <textarea id=contactMe rows=4 cols=40 placeholder='Enter your comment...'></textarea>
  <script src="contactBox.js">
  </script>
</body>
</html>

您也可以这样做:

function clearText(field){
	if(field.defaultValue == field.value){
		field.value = "";
	}
	else if(field.value == ""){
		field.value = field.defaultValue;
	}
}
<html>
<body>
  <textarea id=contactMe rows=4 cols=40 onfocus="clearText(this);" onblur="clearText(this);">Enter your comment...</textarea>
</body>
</html>

您可以使用占位符属性来做到这一点

<html>
<body>
  <textarea id="contactMe" rows="4" cols="40" placeholder="Enter your comment..."></textarea>
  <script src="contactBox.js">
  </script>
</body>
</html>

请注意IE8不支持此功能,您必须使用javascript

我最喜欢的插件是Mathias。如果你需要支持IE8,那就试试吧。你也没有使用双引号在你的html属性(id="contactMe")。(虽然没有引号也可以工作,但w3建议使用引号)

如果你需要一个完整的jQuery解决方案,你可以使用下面的代码。这是小提琴

var placeholderText = "Enter your comment...";
$(document).on("click","#contactMe",function(e){
 if($(this).val()=="" ||$(this).val() == placeholderText ){
  $(this).val("");
}
});
$(document).on("focusout","#contactMe",function(e){
    if($(this).val()==""){
      $(this).val(placeholderText);
    }
});
$(document).ready(function(){
 $("#contactMe").val(placeholderText);
});