【发布时间】:2022-11-16 23:34:58
【问题描述】:
您好,有没有其他方法可以得到与我们向下看到的相同的结果 目标是:用一个按钮和函数改变“src”属性
<img id="image" src="path of picture1" width="160" height="120">
<button type="button" onclick="test()">over here </button>
<script>
let smile = true
let test = () => {
if (smile == true) {
document.getElementById("image").src = "path of picture2";
smile = false
} else {
document.getElementById("image").src = "path of picture1";
smile = true
}
}
</script>
每当我单击按钮时,浏览器都会显示 picture2 然后如果我再次单击会显示 picture1 这可以一遍又一遍地完成,请为此分享您的解决方案
【问题讨论】:
-
究竟是什么问题?您的代码使得单击一次将设置图像以在下一次单击时更改。
-
我只想知道是否有其他解决方案
-
还有很多其他方法,但你的方法没有错(除了你应该只在函数执行之前获取对图像的引用一次,这样你就不必一遍又一遍地在 DOM 中搜索相同的元素再次)。
-
你能告诉我最好的优化 true 和 falls 语句就像一块方糖,每当我无法解决我使用它的问题时。想要一些创意
-
@ErfanTa Wdym 你想要创造力。你有一个有效的代码,所以使用它?!为什么要改变它
标签: javascript html dom