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

时间:2016-10-21 21:59:02

标签: javascript

我希望在点击用户名框时文本消失,我是否正确使用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>

3 个答案:

答案 0 :(得分:4)

使用value属性,而不是直接更改placeholder(一种hacky并且容易出现并发症)。这是为了做到这一点 - 不需要javascript。

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

答案 1 :(得分:1)

文本框只有name "username"。您还需要为其提供id属性。

<input type="text" value="Unique ID" name="username" id="username">

注意javascript函数如何被称为getElementBy Id ? :)这意味着它需要一个Id!

答案 2 :(得分:1)

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

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