【问题标题】:Need help javascript需要帮助 javascript
【发布时间】:2017-10-05 08:49:59
【问题描述】:

我想知道在下面的代码中,当我引用一个元素时 by (document.getElementById) 并使其等于一个用于验证目的的变量,为什么我不能在 javascript 中使用 name 而不是 name1。

function validation() {
  name1 = document.getElementById('name');
  if (name1.value == "") {

    alert('this field cannot left empty');
    return false;
  }
}
<form id="form" action="message.html" method="post" onSubmit='return validation()' />
<input type="text" placeholder="enter your name" id='name' />
<input type="text" placeholder="address" id='address' />
<input type="tel" placeholder="telephone" id="telephone" />
<input type="submit" value="submit">

【问题讨论】:

  • 尝试使用控制台... F12
  • 你是说你不能使用name=document.getElementById('name');
  • 是的,在这种情况下,我不能使用与元素 ID 相同的变量名。
  • 使用var name=document.getElementById('name');
  • 这行得通!试试看,让我们知道..

标签: javascript html


【解决方案1】:

var 添加到name1 后,代码将开始执行。添加 var 后,您也可以将 document.getElementById('name') 分配给 name 并且它会起作用。您可以运行以下 sn -p 以供参考。

function validation(){
    var name=document.getElementById('name');
    if(name.value== ""){
        alert('this field cannot left empty');
        return false;
     }
}
<form id="form" action="message.html" method="post"
 onSubmit='return validation()'>
    <input type="text" placeholder="enter your name" id='name' />
    <input type="text" placeholder="address" id='address' />
    <input type="tel" placeholder="telephone" id="telephone" />
    <input type="submit" value="submit">
</form>

【讨论】:

  • 您需要将input-元素放在form-标签内。 &lt;form&gt;&lt;input/&gt;&lt;input/&gt;&lt;/form&gt;
  • 代码中还有一个问题:&lt;form id="form" action="message.html" method="post" onSubmit='return validation()' /&gt; 最后必须是&gt;
  • 面对手掌。这就是为什么复制粘贴有时不起作用的原因
【解决方案2】:

尝试使用这个..

您忘记declare 变量。 如果你使用variableassignmentmust declare it 在使用之前。

如需更多参考,您可以在 SO,What is the purpose of the var keyword and when to use it (or omit it)? 中查找此热门主题

function validation(){
    var name = document.getElementById('name');
    if(name.value== ""){
        alert('this field cannot left empty');
    return false;
   }
}

【讨论】:

  • 非常感谢,所以声明变量总是好的。我以为如果我不声明变量 javascript 仍然会将它用作变量。
  • @AliRaza 有关var 的说明,您可以咨询stackoverflow.com/questions/1470488/…。在使用之前声明一个变量总是好的做法。
【解决方案3】:
var name=document.getElementById('name');

您应该在元素名称之前使用 var。

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2012-10-03
    • 2012-10-04
    相关资源
    最近更新 更多