使用.onclick运行函数时,它不执行它。我做错了什么吗?
<script>
const object1 = document.getElementById('object1');
const image2Path = "image2.svg";
object1.onclick = () => {
object1.src = image2Path;
}
</script>
<body>
<img id='object1' src="image1.svg">
</body>
当我点击对象时,我期待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>
const object1 = document.getElementById('object1');
const image2Path = "image2.svg";
object1.onclick = () => {
object1.src = image2Path;
}
<body>
<img id='object1' src="image1.svg">
</body>