gpt4 book ai didi

javascript - 如何重用javascript来切换图像来源

转载 作者:行者123 更新时间:2023-11-28 15:01:48 24 4
gpt4 key购买 nike

我在网页中有一些简单的按钮,其中 OnClick 一个小脚本将更改要显示的图像的来源,但是我正在查看此内容并认为我正在一遍又一遍地重新编写相同的代码,但我无法不知道如何更改图像而不在新函数中指定 src="X.jpg"每次查找新文件,也许有更好的解决方案?

这是我到目前为止所得到的。

    <article class="large-text-area">
<button onclick="myFunction1()">Click Here to view image</button>

<script>
function myFunction1() {
document.getElementById("theImage").src = "../media/img/sketch/strip1.jpeg"
}
</script>
</article>

<!-- Section 2 -->
<article class="large-text-area">
<button onclick="myFunction2()">Click Here to view image</button>

<script>
function myFunction2() {
document.getElementById("theImage").src = "../media/img/sketch/strip2.jpeg"
}
</script>
</article>

<!-- Section 3 -->
<article class="large-text-area">
<button onclick="myFunction3()">Click Here to view image</button>

<script>
function myFunction3() {
document.getElementById("theImage").src = "../media/img/sketch/strip3.jpeg"
}
</script>
</article>

任何建议都会有用,谢谢!

最佳答案

我认为您正在寻找类似于单个函数的东西来使用正确的源更新图像,对吗?

function changeImgSrc(imageId) {
document.getElementById("theImage").src = "../media/img/sketch/strip" + imageId + ".jpeg";
}
<img id="theImage" src=""/>

<!-- Section 1 -->
<article class="large-text-area">
<button onclick="changeImgSrc('1')">Click Here to view image</button>
</article>

<!-- Section 2 -->
<article class="large-text-area">
<button onclick="changeImgSrc('2')">Click Here to view image</button>
</article>

<!-- Section 3 -->
<article class="large-text-area">
<button onclick="changeImgSrc('3')">Click Here to view image</button>
</article>

使用开关可能是最佳实践。

function changeImgSrc(imageId) {
var imgSrcValue;

switch (imageId) {
case 1:
imgSrcValue = "../media/img/sketch/strip1.jpeg";
break;
case 2:
imgSrcValue = "../media/img/sketch/strip2.jpeg";
break;
case 3:
imgSrcValue = "../media/img/sketch/strip3.jpeg";
break;
}

document.getElementById("theImage").src = imgSrcValue;
}
<img id="theImage" src=""/>

<!-- Section 1 -->
<article class="large-text-area">
<button onclick="changeImgSrc(1)">Click Here to view image</button>
</article>

<!-- Section 2 -->
<article class="large-text-area">
<button onclick="changeImgSrc(2)">Click Here to view image</button>
</article>

<!-- Section 3 -->
<article class="large-text-area">
<button onclick="changeImgSrc(3)">Click Here to view image</button>
</article>

关于javascript - 如何重用javascript来切换图像来源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40617366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com