简体   繁体   English

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

[英]TypeError: document.getElementById(…) is null Django + JS

I'm having an error while executing the following code: 执行以下代码时出现错误:

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: 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>

This code fails with the following error: 此代码失败,并出现以下错误:

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

I'm including JavaScript on my base.html file and page1.html extends this file. 我在base.html文件中包含JavaScript,而page1.html扩展了该文件。

My base.html <head> : 我的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() didn't help window.onload()没有帮助

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

Your javascript file is running before the button exists in the DOM, so it can not find it 您的javascript文件在该按钮存在于DOM中之前就已经在运行,因此无法找到它

wrapper your code with use window.onload 使用window.onload包装代码

whenever you access a DOM element, it must already be rendered 每当您访问DOM元素时,它都必须已经呈现

Perform a null checker 执行null检查器

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

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

如果要添加侦听器,则必须消除Button的type="submit"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM