Javascript代码:我希望文本框在聚焦时为空

Javascript code: I want the text box to be empty when on focus

本文关键字:聚焦 代码 我希望 文本 Javascript      更新时间:2023-09-26

当用户名框被点击时,我想要文本消失,我是否正确使用onfocus?我做错了什么,请帮帮我。

 document.getElementById("username").onfocus = function() {
   document.getElementById("username").value = "";
 }
<form name="Sign Up">
  <fieldset>
    <legend><i><b>Siqn Up</b></i>
    </legend>
    <p>
      <label for="username">Username</label>
      <input type="text" value="Unique ID" name="username">
    </p>
    <p>
      <label for="email">Email</label>
      <input type="text" name="email">
    </p>
    <p>
      <label for="password">Password
        <input type="password" name="password">
      </label>
    </p>
    <input type="submit" value="Sign Up">
  </fieldset>
</form>

使用placeholder属性而不是直接更改value(有点粗糙且容易引起复杂)。它就是用来做这个的——不需要javascript。

<input type="text" name="username" placeholder="Unique ID">

文本框中只有"username"中的name。你还需要给它一个id属性。

<input type="text" value="Unique ID" name="username" id="username">
注意javascript函数如何被称为getElementById?:)这意味着它需要一个Id!

您正在使用getElementById并传递"name"属性作为参数,该参数将永远不会被找到,因此使用getElementsByName:

 document.getElementsByName("username")[0].onfocus=function()
 document.getElementsByName("username")[0].value = "";