Javascript在直接在模板中键入时有效,但在从src文件导入时则不工作



这个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>

这在填充选择.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
  • 脚本在它尝试使用 DOM 访问的 HTML 之前或之后

你选择了两个错误中的一个来归咎于你的问题。

在 DOM 元素存在之前,您无法访问它们。

最新更新