首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >单击单个按钮可更改页面上的多个相关图像。如何使其适用于多个按钮,每个按钮都有多个相关图像?

单击单个按钮可更改页面上的多个相关图像。如何使其适用于多个按钮,每个按钮都有多个相关图像?
EN

Stack Overflow用户
提问于 2018-04-27 11:51:16
回答 1查看 22关注 0票数 0

下面的代码用于在单击单个按钮时更改同一页上的多个相关图像:

代码语言:javascript
复制
<!-- RR buttons -->
<div class="wrapper-9">
<button onclick="changeImage()" id="2" class="box">2</button>
</div>

<!-- RR images -->
<img id="theFirstImage" src="RR/images/singles/RR-1.png">
<img id="theSecondImage" src="RR/images/rhythm-1.png">
<img id="theThirdImage" src="RR/images/riff-1.png">


<script>
function changeImage()
{
document.getElementById('theFirstImage').src="RR/images/singles/RR-2.png";
document.getElementById('theSecondImage').src="RR/images/rhythm-2.png";
document.getElementById('theThirdImage').src="RR/images/riff-2.png";
}
</script>

如何调整此代码以适应多个不同的按钮,而不仅仅是一个按钮?我总共有54个按钮。我的命名约定确保按钮和图像都通过数字相关:也就是说,按钮"2“对应于图像"RR-2.png”、“节奏-2.png”和"riff-2.png";按钮"46“对应于"RR-46.png”、“节奏-46.png”和"riff-46.png“。解决方案必须从给定按钮的id中提取数字,然后将其插入到源调用中……但我想不出该怎么做。我试过了,但没有用:

代码语言:javascript
复制
<!-- RR buttons -->
<div class="wrapper-9">
<button onclick="changeImage()" id="1" class="box">1</button>
<button onclick="changeImage()" id="2" class="box">2</button>
<button onclick="changeImage()" id="3" class="box">3</button>
</div>

<!-- RR images -->
<img id="theFirstImage" src="RR/images/singles/RR-1.png">
<img id="theSecondImage" src="RR/images/rhythm-1.png">
<img id="theThirdImage" src="RR/images/riff-1.png">

<script>
function changeImage()
{
var currentLabel = $(this).closest('.box').find('button').attr("id");
document.getElementById('theFirstImage').src="RR/images/singles/RR-'" + currentLabel + "'.png";
document.getElementById('theSecondImage').src="RR/images/rhythm-'" + currentLabel + "'.png";
document.getElementById('theThirdImage').src="RR/images/riff-'" + currentLabel + "'.png";
}
</script>

欢迎大家深入了解我做错了什么!

EN

回答 1

Stack Overflow用户

发布于 2018-04-27 19:01:04

啊,解决了!在这里找到了答案:JavaScript - onClick to get the ID of the clicked button

代码语言:javascript
复制
<!-- RR buttons -->
<div class="wrapper-9">
<button class="box" id="1" onClick="reply_click(this.id)">1</button>
<button class="box" id="2" onClick="reply_click(this.id)">2</button>
<button class="box" id="3" onClick="reply_click(this.id)">3</button>
</div>

<!-- RR images -->
<img id="theFirstImage" src="RR/images/singles/RR-1.png">
<img id="theSecondImage" src="RR/images/rhythm-1.png">
<img id="theThirdImage" src="RR/images/riff-1.png">


<script type="text/javascript">
function reply_click(clicked_id)
{
document.getElementById('theFirstImage').src="RR/images/singles/RR-" + clicked_id + ".png";
document.getElementById('theSecondImage').src="RR/images/rhythm-" + clicked_id + ".png";
document.getElementById('theThirdImage').src="RR/images/riff-" + clicked_id + ".png";
}
</script>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50054955

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档