【问题标题】:Error return as the JS file is looking for top function in all HTML filesJS 文件在所有 HTML 文件中查找顶级函数时返回错误
【发布时间】:2021-03-17 17:10:10
【问题描述】:

我将保持简单:

  • 1个JS文件
  • 3 个 HTML 文件(名称:汽车、树木、房屋)
  • 1 个 CSS 文件。

所有的函数都扔进了JS文件。但问题是,如果我单击 Cars 中的提交“按钮”,JS 文件将从顶部的(树的)函数开始并查找 addEventListener,如果找不到它会返回错误“无法读取属性 'addEventListener' of null' - 问题出在:

tree_form.addEventListener('submit', e => {

我只想让 Js 文件执行 HTML 文件要求它执行的功能。 所以在这种情况下,它是跟随树函数的“汽车”函数。

如果我将所有内容分开并将其放入单独的项目中,或者将 JS 与引用的 HTML 文件一起放入,则一切正常,只有当我将所有函数放在一个 JS 文件中时才会出现问题。

HTML 汽车

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;500&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <title>Car Form</title>
</head>

<body>
 <div class="cars-body">
   <div class="car_container">
     <div class="car_heading_form">
       <h2> Car Form</h2>
     </div>
     <form id="car_form" class="car_form">
       <div class="car-form-control">
         <label for="carName">Car Name</label>
         <input type="text" placeholder="hank" id="carName" />
         <i class="fas fa-check-circle"></i>
         <i class="fas fa-exclamation-circle"></i>
         <small>Error message</small>
       </div>
       <div class="car-form-control">
         <label for="carColor">Car Color</label>
         <input type="text" placeholder="Gold" id="carColor" />
         <i class="fas fa-check-circle"></i>
         <i class="fas fa-exclamation-circle"></i>
         <small>Error message</small>
       </div>
       <button>Submit</button>
     </form>
   </div>
 </div>
</body>

<script src="script.js"></script>


</html>

JS

// Tree Form
const tree_form = document.getElementById('tree_form');
const treeName = document.getElementById('treeName');
const treeHeight = document.getElementById('treeHeight');

tree_form.addEventListener('submit', e => {
    e.preventDefault();

    tree_Inputs();
});

function tree_Inputs() {
    //trim to remove the whitespaces
    const treerNameValue = treeName.value.trim();
    const treeHeightValue = treeHeight.value.trim();

    if (treeNameValue === '') {
        setErrorForTree(treeName, 'Please enter a name');
    } else {
        setSuccessForTree(treeName);
    }

    if (treeHeightValue === '') {
        setErrorForTree(treeHeight, 'Please enter a number.');
    } else {
        setSuccessForTree(treeHeight);
    }
}

function setErrorForTree(input, message) {
    const formControlTree = input.parentElement;
    const small = formControlTree.querySelector('small');
    formControlTree.className = 'tree-form-control error';
    small.innerText = message;
}

function setSuccessForTree(input) {
    const formControlTree = input.parentElement;
    formControlCar.className = 'tree-form-control success';
}



// Car Form
const car_form = document.getElementById('car_form');
const carName = document.getElementById('carName');
const carColor = document.getElementById('carColor');

car_form.addEventListener('submit', e => {
    e.preventDefault();

    car_Inputs();
});

function car_Inputs() {
    //trim to remove the whitespaces
    const carNameValue = carName.value.trim();
    const carColorValue = carColor.value.trim();

    if (carNameValue === '') {
        setErrorForCar(carName, 'Please enter a name');
    } else {
        setSuccessForCar(carName);
    }

    if (carColorValue === '') {
        setErrorForCar(carColor, 'Please a color.');
    } else {
        setSuccessForCar(carColor);
    }
}

function setErrorForCar(input, message) {
    const formControlCar = input.parentElement;
    const small = formControlCar.querySelector('small');
    formControlCar.className = 'car-form-control error';
    small.innerText = message;
}

function setSuccessForCar(input) {
    const formControlCar = input.parentElement;
    formControlCar.className = 'car-form-control success';
}

CSS

  /***** CONTACT US PAGE CSS *****/

  * {
      box-sizing: border-box;
  }

  .car-body, tree-body {
      min-height: 1300px;
      width: 100%;
      background-color: blue;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      margin: 0px;
  }

  .car_container, .tree_container {
      background-color: #fff;
      border-radius: 5px;
      box-shadow: 0 2px 5px rgb(0 0 0 / 30%);
      overflow: hidden;
      width: 600px;
      max-width: 100%;
  }

  .car_heading_form,   .tree_heading_form {
      border-bottom: 1px solid #f0f0f0;
      background-color: #f7f7f7;
      padding: 20px 40px;
  }

.car_heading_form h2  {
   margin: 0px;
      color: Blue;
} 

.tree_heading_form h2 {
      margin: 0px;
      color: green;
  }

  .car_form, .tree_form {
      padding: 30px 40px;
  }

  .car-form-control, .tree-form-control  {
      margin-bottom: 10px;
      padding-bottom: 20px;
      position: relative;
  }

  .car-form-control label, .tree-form-control label {
      display: inline-block;
      margin-bottom: 5px;
      font-weight: 530;
      font-size: 17px;
  }

  .car-form-control input, .tree-form-control input {
      border: 2px solid #f0f0f0;
      border-radius: 4px;
      display: block;
      font-size: 14px;
      padding: 10px;
      width: 100%;
  }

  .car-form-control input:focus, .tree-form-control input:focus {
      outline: 0;
      border-color: #777;
  }

  .car-form-control.success input, .tree-form-control.success input {
      border-color: green;
  }

  .car-form-control.error input,   .tree-form-control.error input {
      border-color: red;
  }


  .car-form-control i,   .tree-form-control i {
      visibility: hidden;
      position: absolute;
      top: 40px;
      right: 10px;
  }

  .car-form-control.success i.fa-check-circle,   .tree-form-control.success i.fa-check-circle {
      color: green;
      visibility: visible;
  }

  .car-form-control.error i.fa-exclamation-circle,   .tree-form-control.error i.fa-exclamation-circle {
      color: red;
      visibility: visible;
  }

  .car-form-control small, .tree-form-control small {
      color: red;
      position: absolute;
      bottom: 0;
      left: 0;
      visibility: hidden;
  }

  .car-form-control.error small, .tree-form-control.error small {
      visibility: visible;
  }

  .car_form button {
      background-color: rgb(31, 136, 229);
      border: 2px solid rgb(128, 128, 128, 0.199);
      border-radius: 4px;
      color: #fff;
      display: block;
      font-size: 16px;
      padding: 10px;
      margin-top: 20px;
      width: 50%;
      cursor: pointer;
  }

  .car_form button:hover {
      cursor: pointer;
      box-shadow: 1px 1px 1px rgb(25, 60, 173);
  }

【问题讨论】:

  • 在 html 中没有 id="tree_form" 以引用 document.getElementById('tree_form'); 。在 js 中使用 html 输入的 id 名称。

标签: javascript html css forms


【解决方案1】:

有两种方法可以解决这个问题。

  1. 如果我需要在一个 JS 中添加很多东西,我更愿意在 JS 中创建一个命名空间。

    var yourNamespace = {

     Car: function() {
     },
    
     Tree: function() {
     },
     House: function() { 
     }
    

    };

当您点击提交时,最后调用它yourNamespace.Car()。

这是一个工作场景:

    var yourNamespace = {};
yourNamespace = {

    Tree: function() {
const tree_form = document.getElementById('tree_form');
const treeName = document.getElementById('treeName');
const treeHeight = document.getElementById('treeHeight');

tree_form.addEventListener('submit', e => {
    e.preventDefault();

    tree_Inputs();
});

function tree_Inputs() {
    //trim to remove the whitespaces
    const treerNameValue = treeName.value.trim();
    const treeHeightValue = treeHeight.value.trim();

    if (treeNameValue === '') {
        setErrorForTree(treeName, 'Please enter a name');
    } else {
        setSuccessForTree(treeName);
    }

    if (treeHeightValue === '') {
        setErrorForTree(treeHeight, 'Please enter a number.');
    } else {
        setSuccessForTree(treeHeight);
    }
}

function setErrorForTree(input, message) {
    const formControlTree = input.parentElement;
    const small = formControlTree.querySelector('small');
    formControlTree.className = 'tree-form-control error';
    small.innerText = message;
}

function setSuccessForTree(input) {
    const formControlTree = input.parentElement;
    formControlCar.className = 'tree-form-control success';
}

    },

    Car: function() {
const car_form = document.getElementById('car_form');
const carName = document.getElementById('carName');
const carColor = document.getElementById('carColor');

car_form.addEventListener('submit', e => {
    e.preventDefault();

    car_Inputs();
});

function car_Inputs() {
    //trim to remove the whitespaces
    const carNameValue = carName.value.trim();
    const carColorValue = carColor.value.trim();

    if (carNameValue === '') {
        setErrorForCar(carName, 'Please enter a name');
    } else {
        setSuccessForCar(carName);
    }

    if (carColorValue === '') {
        setErrorForCar(carColor, 'Please a color.');
    } else {
        setSuccessForCar(carColor);
    }
}

function setErrorForCar(input, message) {
    const formControlCar = input.parentElement;
    const small = formControlCar.querySelector('small');
    formControlCar.className = 'car-form-control error';
    small.innerText = message;
}

function setSuccessForCar(input) {
    const formControlCar = input.parentElement;
    formControlCar.className = 'car-form-control success';
}
    },
    House: function() { 
    }

};
* {
      box-sizing: border-box;
  }

  .car-body, tree-body {
      min-height: 1300px;
      width: 100%;
      background-color: blue;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      margin: 0px;
  }

  .car_container, .tree_container {
      background-color: #fff;
      border-radius: 5px;
      box-shadow: 0 2px 5px rgb(0 0 0 / 30%);
      overflow: hidden;
      width: 600px;
      max-width: 100%;
  }

  .car_heading_form,   .tree_heading_form {
      border-bottom: 1px solid #f0f0f0;
      background-color: #f7f7f7;
      padding: 20px 40px;
  }

.car_heading_form h2  {
   margin: 0px;
      color: Blue;
} 

.tree_heading_form h2 {
      margin: 0px;
      color: green;
  }

  .car_form, .tree_form {
      padding: 30px 40px;
  }

  .car-form-control, .tree-form-control  {
      margin-bottom: 10px;
      padding-bottom: 20px;
      position: relative;
  }

  .car-form-control label, .tree-form-control label {
      display: inline-block;
      margin-bottom: 5px;
      font-weight: 530;
      font-size: 17px;
  }

  .car-form-control input, .tree-form-control input {
      border: 2px solid #f0f0f0;
      border-radius: 4px;
      display: block;
      font-size: 14px;
      padding: 10px;
      width: 100%;
  }

  .car-form-control input:focus, .tree-form-control input:focus {
      outline: 0;
      border-color: #777;
  }

  .car-form-control.success input, .tree-form-control.success input {
      border-color: green;
  }

  .car-form-control.error input,   .tree-form-control.error input {
      border-color: red;
  }


  .car-form-control i,   .tree-form-control i {
      visibility: hidden;
      position: absolute;
      top: 40px;
      right: 10px;
  }

  .car-form-control.success i.fa-check-circle,   .tree-form-control.success i.fa-check-circle {
      color: green;
      visibility: visible;
  }

  .car-form-control.error i.fa-exclamation-circle,   .tree-form-control.error i.fa-exclamation-circle {
      color: red;
      visibility: visible;
  }

  .car-form-control small, .tree-form-control small {
      color: red;
      position: absolute;
      bottom: 0;
      left: 0;
      visibility: hidden;
  }

  .car-form-control.error small, .tree-form-control.error small {
      visibility: visible;
  }

  .car_form button {
      background-color: rgb(31, 136, 229);
      border: 2px solid rgb(128, 128, 128, 0.199);
      border-radius: 4px;
      color: #fff;
      display: block;
      font-size: 16px;
      padding: 10px;
      margin-top: 20px;
      width: 50%;
      cursor: pointer;
  }

  .car_form button:hover {
      cursor: pointer;
      box-shadow: 1px 1px 1px rgb(25, 60, 173);
  }
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;500&display=swap" rel="stylesheet">
   
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <div class="cars-body">
   <div class="car_container">
     <div class="car_heading_form">
       <h2> Car Form</h2>
     </div>
     <form id="car_form" class="car_form">
       <div class="car-form-control">
         <label for="carName">Car Name</label>
         <input type="text" placeholder="hank" id="carName" />
         <i class="fas fa-check-circle"></i>
         <i class="fas fa-exclamation-circle"></i>
         <small>Error message</small>
       </div>
       <div class="car-form-control">
         <label for="carColor">Car Color</label>
         <input type="text" placeholder="Gold" id="carColor" />
         <i class="fas fa-check-circle"></i>
         <i class="fas fa-exclamation-circle"></i>
         <small>Error message</small>
       </div>
       <button onClick="yourNamespace.Car()">Submit</button>
     </form>
   </div>
   </div>
 
  1. 检查 id 哪个表单当前可见(在您的情况下不宜使用,最好使用 JS 提供的功能)

【讨论】:

  • 我认为这将是最好的选择,因为除了表单之外我还有其他需要调用的东西,因此我可以将它们全部分配给命名空间
  • 我对一件事感到困惑。您的第一条指令 'var youNamespace{ car​​ function() etc...' 是否位于 JS 文件的顶部?然后按照这个你会写'var yourNamespace = {};你的命名空间 = {
  • 后跟汽车:function() { Tree: function() { const tree_form = document.getElementById('tree_form'); const treeName = document.getElementById('treeName'); const treeHeight = document.getElementById('treeHeight'); tree_form.addEventListener('submit', e => { e.preventDefault(); tree_Inputs(); });
  • 我没有得到你的问题。但主要的事情 var yourNamespace = {};在第一行。它是一个声明,然后 yourNamespace 中的所有函数都将保持原样。所以如果你用这个替换你的js,它会起作用。如果你正确地格式化你的代码,你就会知道它的样子(yourNamespace.Car / yourNamespace.Tree/ yourNamespace.House)
  • 第一行我声明 'var yourNamspace = { Car: function(), Tree: function(), House function()' 第二行我直接进入' yourNamespace { Tree: function() { const tree_form = document.getElementById('tree_form'); const treeName = document.getElementById('treeName'); const treeHeight = document.getElementById('treeHeight'); ......等等......'我不需要把'var yourNamespace ={};'在第 1 行和第 2 行之间(如上)再次重新声明 yourNamespace? -希望更有意义
【解决方案2】:

您似乎期待 JavaScript 神奇地知道它在哪个表单上以及要运行哪个代码。对不起。 JavaScript 不是魔法。

试试类似的东西

const tree_form = document.getElementById('tree_form');
const car_form = document.getElementById('car_form');

if (tree_form) {
  // all the tree code
}
else if (car_form) {
  // all the car code
}

【讨论】:

    【解决方案3】:

    如果您再次点击提交按钮,而另一个输入字段中没有任何值,则必须正确显示消息。这是没有你的 css 的汽车的 javascript。

    // Car Form
    const car_form = document.getElementById('car_form');
    const carName  = document.getElementById('carName');
    const carColor = document.getElementById('carColor');
    
    car_form.addEventListener('submit', e => {
        e.preventDefault();
        car_Inputs();
    });
    
    function car_Inputs() {
        //trim to remove the whitespaces
        const carNameValue  = carName.value.trim();
        const carColorValue = carColor.value.trim();
        
        setErrorForCar(carName, 'Message');
        if (carNameValue === '') {
            setErrorForCar(carName, 'Please enter a name');
        } else {
            setSuccessForCar(carName);
        }
    
        setErrorForCar(carColor, 'Message');
        if (carColorValue === '') {
            setErrorForCar(carColor, 'Please enter a color.');
        } else {
            setSuccessForCar(carColor);
        }
    }
    
    function setErrorForCar(input, message) {
        const formControlCar = input.parentElement;
        const small = formControlCar.querySelector('small');
        formControlCar.className = 'car-form-control error';
        small.innerText = message;
    }
    
    function setSuccessForCar(input) {
        const formControlCar = input.parentElement;
        formControlCar.className = 'car-form-control success';
    }
    <div class="cars-body">
       <div class="car_container">
         <div class="car_heading_form">
           <h2> Car Form</h2>
         </div>
         <form id="car_form" class="car_form">
           <div class="car-form-control">
             <label for="carName">Car Name</label>
             <input type="text" placeholder="hank" id="carName" />
             <i class="fas fa-check-circle"></i>
             <i class="fas fa-exclamation-circle"></i>
             <small>Message</small>
           </div>
           <div class="car-form-control">
             <label for="carColor">Car Color</label>
             <input type="text" placeholder="Gold" id="carColor" />
             <i class="fas fa-check-circle"></i>
             <i class="fas fa-exclamation-circle"></i>
             <small>Message</small>
           </div>
           <button>Submit</button>
         </form>
       </div>
     </div>

    【讨论】:

      猜你喜欢
      • 2015-12-21
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      • 2016-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多