[英]Can't include JS file into HTML
我有 HTML 和 JS 文件的簡單文件結構,如下所示:
templates/
- index.html
- menuselector.js
這是我想導入 HTML 的 function 示例:
export function getTypeOfClient() {
const select = document.getElementById('inputGroupSelect02');
const value = select.options[select.selectedIndex].value;
if (value === '1') {
document.getElementById('person').style.display = "block";
document.getElementById('company').style.display = "none";
} else if (value === '2') {
document.getElementById('company').style.display = "block"
document.getElementById('person').style.display = "none";
} else {
document.getElementById('person').style.display = "none";
document.getElementById('company').style.display = "none";
}
}
這是使用此 function 的 HTML 代碼示例:
<select class="form-select" id="inputGroupSelect03" onchange="getTypeOfClient()">
<option value="0" selected>Choose...</option>
<option value="1">Person</option>
<option value="2">Company</option>
</select>
當我在script
標簽中編寫代碼時,一切正常,但我決定將此代碼導出到 JS 文件中以使其更干凈。
我在這樣的文件中導入它 - <script type="text/javascript" src="menuselector.js"></script>
這就是問題所在。 每次在控制台中我得到 404 並沒有找到這個文件。 我試圖在 header、頁腳、正文等中導入它,但它不起作用。 我做錯了什么?
您不能將 ES 模塊用作內聯事件偵聽onchange="getTypeOfClient()"
因為它們沒有被添加到全局 scope (這是模塊的全部要點)。
使用window.getTypeOfClient = getTypeOfClient
將其顯式分配給全局 scope ,或者如果您不想要 ES 模塊,則刪除export
關鍵字。
話雖如此,使用內聯事件偵聽器非常糟糕,原因有很多。 而是使用 Javascript 來定義或添加監聽器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.