我有13张小图片和13张大图片,如果点击任何小图片它会显示相关的大图片,我只是想知道是否有可能推广点击功能所以我没有必要重复这个dame代码13次,谢谢
<div id="press_images">
<img id="s1" class="small" src="images/press/small/1.png" />
<img id="s2" class="small" src="images/press/small/2.png" />
<img id="s3" class="small" src="images/press/small/3.png" />
<img id="s4" class="small" src="images/press/small/4.png" />
.....
<img id="s13" class="small" src="images/press/small/13.png" />
</div>
<div class="big">
<a id="close">X</a>
<img id="b1" src="images/press/big/1.jpg" />
......
<img id="b13" src="images/press/big/13.jpg" />
</div>
$("#s1").click(function(){
$('#b1').show();
$('.big').show(300);
return false;
});
所以我想知道我是否可以更改$(“#s1”)。点击(function()所以我不必重复13次。
感谢
答案 0 :(得分:1)
试试这个
// For all <img>'s with class `small`
$("img.small").click(function() {
// Get the index from the small image's ID
var index = this.id.substr(1);
// Hide all other big images
$(".big img").hide()
// Show the related big images
$('#b' + index).show();
// Show the big image container
$('.big').show(300);
return false;
});
答案 1 :(得分:1)
以下内容应该有效:
$(".small").click(function(){
var id_img=$(this).attr('id').replace('s','');
$('.big img').hide();
$('#b'+id_img).show();
$('.big').show(300);
return false;
});
答案 2 :(得分:1)
我就是这样做的:
<div id="press_images">
<img id="s1" rel="b1" class="small" src="images/press/small/1.png" />
<img id="s2" rel="b2" class="small" src="images/press/small/2.png" />
</div>
<div class="big">
<a id="close">X</a>
<img id="b1" class="big" src="images/press/big/1.jpg" />
<img id="b2" class="big" src="images/press/big/2.jpg" />
</div>
$(".small").click(function(){
$( ".big img" ).hide();
$( "#"+ $(this).attr("rel") ).show();
}
请注意,我使用“rel
”链接元素。我认为它比假设b1与s1相关更清晰。我喜欢CoC,但我不确定在那种情况下它是最好的主意。
答案 3 :(得分:0)
在每张图片中放一个课程。例如:
<img id="s1" class="small clickable-image" src="images/press/small/1.png" />
然后:
$(".clickable-image").click(function(){
$('#b1').show();
$('.big').show(300);
return false;
});
编辑:当然,您必须更改行$('#b1')。show();但是,它很简单,你只需要获取元素ID并构建更大图像的ID。就像贾斯汀约翰逊的回答一样。
答案 4 :(得分:0)
<div id="press_images">
<img id="small1" class="small small-img" src="images/press/small/1.png" />
<img id="small2" class="small small-img" src="images/press/small/2.png" />
<img id="small3" class="small small-img" src="images/press/small/3.png" />
<img id="small4" class="small small-img" src="images/press/small/4.png" />
.....
<img id="small13" class="small small-img" src="images/press/small/13.png" />
</div>
<div class="big">
<a id="close">X</a>
<img id="big1" class="big-img" src="images/press/big/1.jpg" />
......
<img id="big13" class="big-img" src="images/press/big/13.jpg" />
</div>
$(".small-img").click(function(e){
var imgBig = String($(this).attr("id")).replace("small", "big");
e.stopPropagation();
$(".big-img").hide();
$("#" + imgBig ).show();
$(".big").show(300);
});
答案 5 :(得分:0)
最灵活的选择是使用index
和eq
并删除所有明确的html帮助程序,例如ID或rel
$('#press_images img').click(function() {
var n = $('#press_images img').index(this);
$(".big img").hide().eq(n).show()
});