[英]JS onclick doesn't work with external js file
我是 JS 新手,我正在嘗試對外部 js 文件中的文本執行 onclick。 這是我的 html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<p class="p">
Use the HTML DOM to assign an "onclick" event to a p element:
</p>
<p class="demo">Click me to change the above text</p>
<script>
window.onload = startListen();
</script>
<script type="text/javascript" src="/1.js"></script>
</body>
</html>
我的.js文件
function startListen() {
var demoElement = document.querySelector(".demo");
var pElement = document.querySelector(".p");
demoElement.onclick = function change() {
pElement.innerHTML = "Text is changed";
};
}
我想單擊 p.demo 並且 pp 中的文本將被更改但不適用於外部文件。 它仍然可以使用像這樣的 html 屬性的內聯語法。
html
<p class="demo" onclick="change()">Click me to change the above text</p>
js
function change() {
var pElement = document.querySelector(".p");
pElement.innerHTML = "Text is changed";
}
我添加了 onload 但不起作用。 你能幫幫我嗎! 謝謝
對於連接外部 js 文件,請使用 <\script>。
然后你需要在 html 腳本中使用腳本標簽。 然后只需使用 html 中的 onlclick 名稱,然后使用 js 文件中的名稱,然后使用您在 onclick 中使用的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.