单击单个按钮可更改页面上的多个相关图像。如何适应多个按钮,每个多个相关图像?

时间:2018-04-27 03:51:16

标签: image onclick getelementbyid

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

<!-- 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”,“rhythm-2.png”和“riff-2.png” “;按钮“46”对应于“RR-46.png”,“rhythm-46.png”和“riff-46.png”。解决方案必须与从给定按钮的id摘录数字,然后将其插入源调用...但我无法弄清楚如何做到这一点。我试过这个,但无济于事:

<!-- 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>

欢迎任何有关我做错事的见解!

1 个答案:

答案 0 :(得分:0)

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

<!-- 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>