使用javascript.onclick函数的正确方法是什么?
当使用.onclick运行函数时,它不会执行它。我做错什么了吗使用javascript.onclick函数的正确方法是什么?,javascript,html,onclick,Javascript,Html,Onclick,当使用.onclick运行函数时,它不会执行它。我做错什么了吗 <script> const object1 = document.getElementById('object1'); const image2Path = "image2.svg"; object1.onclick = () => { object1.src = image2Path; } </script> <body> <img id='objec
<script>
const object1 = document.getElementById('object1');
const image2Path = "image2.svg";
object1.onclick = () => {
object1.src = image2Path;
}
</script>
<body>
<img id='object1' src="image1.svg">
</body>
const object1=document.getElementById('object1');
const image2Path=“image2.svg”;
object1.onclick=()=>{
object1.src=image2Path;
}
当我单击对象时,我希望image1(成功显示)更改为image2。您需要正确绑定onclick处理程序。这将是一种方法:
<script>
function toogle()
{
const object1 = document.getElementById('object1');
const image2Path = "image2.svg";
object1.src = image2Path;
}
</script>
<body>
<img id='object1' src="image1.svg" onclick="toggle();">
</body>
函数toogle()
{
const object1=document.getElementById('object1');
const image2Path=“image2.svg”;
object1.src=image2Path;
}
const object1=document.getElementById('object1');
const image2Path=“image2.svg”;
object1.onclick=()=>{
object1.src=image2Path;
}
您缺少一个}
。在询问原因之前,请始终检查您的浏览器控制台是否存在错误。您的脚本在浏览器看到object1
@CertainPerformance之前运行,对不起,这是一个输入错误。这在实际文件中不是问题。@tkausl,所以我应该在html文档末尾运行脚本?要么这样,要么将整个脚本放在onload处理程序中。