我想有多个按钮触发一个改变img标签上的src的函数。
每个按钮都会在一个img标签内显示特定图像。它是我希望显示公寓不同楼层平面图的网站,因此按钮显示"类型1","类型2","类型3&# 34;," Type 4"等。
每个项目没有特定数量的类型。
无论有多少选项,我都希望功能正常工作是
我现在有这个,但不知道如何继续
<section id="floor-plans">
<div class="wrapper">
<div class="img-links">
<input type="button" onclick="changeImg()" value="Tipo 1">
<input type="button" onclick="changeImg()" value="Tipo 2">
<input type="button" onclick="changeImg()" value="Tipo 3">
<input type="button" onclick="changeImg()" value="Tipo 4">
<input type="button" onclick="changeImg()" value="Tipo 5">
</div>
<div class="featured-img">
<img src="images/planos/001.jpg" alt="">
</div>
</div>
我可以管理&#34; X&#34;
的选项数量var options = $('img-links input').lenght();
但无法弄清楚如何继续。
此图片更清楚地表示了我想要实现的目标
提前致谢 view image
答案 0 :(得分:0)
您想要使用事件委派。您可以向父级(img-links)添加单击事件,以处理从按钮冒泡的点击。
另外,最好将按钮值与img src分开。
$('.img-links').on('click', 'input', function(){
var src = $(this).attr('data-src');
$('.featured-img img').attr('src', src);
});
删除onclick属性:
<div class="img-links">
<input type="button" value="Tipo 1" data-src="/image01.jpg" />
<input type="button" value="Tipo 2" data-src="/image02.jpg" />
<input type="button" value="Tipo 3" data-src="/image03.jpg" />
<input type="button" value="Tipo 4" data-src="/image04.jpg" />
<input type="button" value="Tipo 5" data-src="/image05.jpg" />
</div>
代码需要在DOM中存在.img-links之后执行,最好是添加$(document).ready(function(){ ... });
,但是可以在添加输入按钮之前执行,这样你就可以在页面加载后动态添加更多它仍然有用。
答案 1 :(得分:0)
Please try again
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function changeImg(src){
$('.featured-img img').attr('src', src);
}
</script>
<section id="floor-plans">
<div class="wrapper">
<div class="img-links">
<input type="button" onclick="changeImg('images/1.jpg')" value="Tipo 1">
<input type="button" onclick="changeImg('images/2.jpg')" value="Tipo 2">
<input type="button" onclick="changeImg('images/3.jpg')" value="Tipo 3">
<input type="button" onclick="changeImg('images/BEST.jpg')" value="Tipo 4">
<input type="button" onclick="changeImg('images/Good.jpg')" value="Tipo 5">
</div>
<div class="featured-img">
<img src="images/1.jpg" alt="">
</div>
</div>
</section>