TypeError:document.getElementById(...)为null Django + JS

时间:2018-08-30 21:25:25

标签: javascript django

执行以下代码时出现错误:

var toppings = ['Zucchini', 'Fresh Garlic', 'Black Olives', 'Anchovies',
  'Barbecue Chicken', 'Artichoke', 'Spinach', 'Ham', 'Sausage', 'Mushrooms'];

var appended = 0;
var maxAppended = 3;

document.getElementById('add').onclick = () => {
  appended+=1;
  if(appended <= maxAppended){
  const topping = document.createElement('select', {
    'name': 'Topping',
    'class': 'form-control'
  });
  list.appendChild(topping);
  toppings.forEach(function(item, i, arr) {
    const ch_topping = document.createElement('option');
    ch_topping.innerHTML += item;
    topping.appendChild(ch_topping);
  });
  }
  else {
      alert('You should stop');
  }
};

page1.html:

 <div class="form-group" id='add_one'>
    <br>
    <h5>You can add up to 3 toppings to your pizza!</h5>
    <ol id="list"></ol>
    <button class="btn btn-primary" id="add" type="submit">Add topping</button>
  </div>

此代码失败,并出现以下错误:

TypeError: document.getElementById(...) is null

我在 base.html 文件中包含了JavaScript,并且 page1.html 扩展了该文件。

我的 base.html <head>

<title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
    <script src="{% static 'js/main.js' %}"></script>

window.onload()没有帮助

jQuery's $(document).ready()没有帮助

3 个答案:

答案 0 :(得分:0)

您的javascript文件在DOM中存在按钮之前就已在运行,因此找不到它

使用window.onload封装代码

每次访问DOM元素时,该元素都必须已经呈现

答案 1 :(得分:0)

执行null检查器

let button = document.getElementById('id');

if(typeof button !== 'undefined' && button !== null) {
  button.onclick = () => { /* Do your stuff */ };
}

答案 2 :(得分:0)

如果要添加侦听器,则必须取消按钮的type="submit"