[英]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.