Clicking on variable ID item triggers function in corresponding variable ID in other object in jQuery

十年热恋 提交于 2019-12-11 09:47:48

问题


I have a series of thumbs which I want a click on one to activate the appearance of the corresponding image. Without writing a script for each thumbnail-image pair I'm looking for a way for an image with id="thumb1" to trigger the appearance of and image with id="photo1" and so on.

I found this answer and tried to implement it thus:

  $(function(){
$('img[id^="thumb"]').click(function () {
    $('img[id^="photo"]').show();
});
});

However, all the thumbs labelled "thumb1", "thumb2" etc all trigger the photo labelled "photo4" (the last in the series).

Any suggestions? Much thanks.


回答1:


Is something like this you want?

$(function(){
    $('img[id^="thumb"]').click(function () {
        var id = $(this).attr('id').replace('thumb', '');
        $('img#photo' + id).toggle();
    });
});

When you click on a thumb, it displays or hides the corresponding photo.



来源:https://stackoverflow.com/questions/8287967/clicking-on-variable-id-item-triggers-function-in-corresponding-variable-id-in-o

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!