我在网页上有一些简单的按钮,其中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>
任何建议都会有用,谢谢!
答案 0 :(得分:4)
我认为你正在寻找一个单一功能的东西,用正确的来源更新图像,对吗?
function changeImgSrc(imageId) {
document.getElementById("theImage").src = "../media/img/sketch/strip" + imageId + ".jpeg";
}
&#13;
<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>
&#13;
使用开关可能是最佳做法。
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;
}
&#13;
<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>
&#13;