0

此 javascript 使用来自变量(名为物理位置)的值填充 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>

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

4

1 回答 1

1

您的代码示例之间有两个区别:

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

您选择了错误的两者之一来归咎于您的问题。

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

于 2017-08-08T12:03:52.680 回答