此 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>
但是,这并没有解决问题。我一定也做错了什么(?)