0
此JavaScript使用來自變量(名爲physical_location)的值填充SelectField。它的工作原理時,JavaScript是直接插在模板中像這樣:JavaScript直接在模板中輸入時工作,但不從src文件導入時工作
<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。因此我修改了模板lie:
<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>
但是,這並沒有解決問題。我一定是做了別人錯了也
如果你把腳本中的DOM元素它應該操作,除非你在domready中事件處理包裝你的代碼將無法正常工作上面。你改變了兩個樣本之間的位置,它與內聯腳本和標籤src無關。 –
嘗試將您的腳本標記放在下方'
我已經修改了我的模板,但建議似乎沒有解決問題。 (見編輯後)。 – apprentice123
回答
有你的代碼樣本兩個不同點(?):
您選擇了錯誤的二者之一來解決您的問題。
You can't access DOM elements before they exist。
來源
2017-08-08 12:03:52 Quentin
我修改了我的模板,但建議似乎沒有解決問題。 – apprentice123
相關問題