Javascript 直接在模板中输入时有效,但从 src 文件导入时无效

Javascript works when typed directly in template, but not when imported from src file

此 javascript 使用变量(名为 physical_location)的值填充 SelectField。当 Javascript 像这样直接插入模板时,它会起作用:

<th> Format {{ form.physical_location(class_='form-control physical_location', value=physical_location) }} </th>

<script> var els = document.getElementsByClassName("physical_location");
    for (i = 0; i < els.length; i++) {
        els[i].value = els[i].getAttribute('value');
}
</script>

但是,当我尝试整理内容并将其放在单独的文件中时,它并没有像以前那样工作。例如,我在模板文件中试过这个:

<script src="static/js/populateselect.js" type="text/javascript"></script>

<th> Format {{ form.physical_location(class_='form-control physical_location', value=physical_location) }} </th>

这在 populateselect.js 中:

var els = document.getElementsByClassName("physical_location");
    for (i = 0; i < els.length; i++) {
        els[i].value = els[i].getAttribute('value');
}

编辑** 答案中建议我的问题与我将 src 放置在模板中的表单上方有关。结果我修改了模板的谎言:

<th> Physical Location {{ form.physical_location(class_='form-control physical_location', value=physical_location) }} </th>
<script src="static/js/populateselect.js" type="text/javascript"></script>

但是,这并没有解决问题。我一定也做错了什么(?)

您的代码示例有两处不同:

  • 脚本是内联的或来自 URL
  • 脚本在 HTML 之前,它尝试使用 DOM 或在
  • 之后访问

您选错了导致您的问题的两个原因之一。

You can't access DOM elements before they exist.