【问题标题】:jQuery on thumbnail click replace second img src with thumbnail src缩略图上的jQuery单击用缩略图src替换第二个img src
【发布时间】:2012-01-01 21:43:53
【问题描述】:

JSFIDDLE HERE 在按下.miniimg/2/3 时,它应该替换我使用 jquery 附加到 div .imgcontainer 的 img 分类 .presentimg 的 src,我已经通过 jQuery (BELOW HTML) 和我认为它不起作用的唯一原因是因为我在函数中使用了函数并且我不知道替代方法

<div class="imgcontainer">
    <div class="minicontainer">
    <img src="http://lh3.googleusercontent.com/_Zuzii37VUO4/Ta0nUeMwXoI/AAAAAAAAFoc/7f0Um7OTgNg/s000/Antartic-by-Peter-Rejcek.jpg" title="icy mountains" class="miniimg"/>
    <img src="http://lh3.googleusercontent.com/_Zuzii37VUO4/Ta0nUFUhg6I/AAAAAAAAFoY/GToUxRYcteY/s000/Antartic-by-Kelly-Speelman.jpg" title="icy planes and hills" class="miniimg2"/>
    <img src="http://lh4.googleusercontent.com/_Zuzii37VUO4/Ta0nTs8AbPI/AAAAAAAAFoU/zCvNKv4kfe4/s000/BeachWaves-By-RePublicDomain.jpg" title="sun rise with clouds" class="miniimg3"/>
    </div>
</div>

jquery,我在 jquery 中使用(索引)作为外部 .each 函数,正如我在论坛上看到的那样,但我不知道这是否真的有效

$(".imgcontainer").each(function(){
    var imgsrc = $(".minicontainer img:first-child").attr("src");
    $(this).append('<img src="'+imgsrc+'" class="presentimg"/>');
});
$(".miniimg").each(function(index){
    var $this = $(this);
    $(this).click(function(){
        var miniimgrc = $this.attr("src");
        $(".presentimg").atrr('src', miniimgrc);
    });
});
$(".miniimg2").each(function(index){
    var $this = $(this);
    $(this).click(function(){
        var miniimgrc2 = $this.attr("src");
        $(".presentimg").atrr('src', miniimgrc2);
    });
});
$(".miniimg3").each(function(index){
    var $this = $(this);
    $(this).click(function(){
        var miniimgrc3 = $this.attr("src");
        $(".presentimg").atrr('src', miniimgrc3);
    });
});

【问题讨论】:

    标签: javascript jquery image each src


    【解决方案1】:

    其实我觉得你的问题是attr有几个拼写错误:

    $(".presentimg").atrr('src', miniimgrc3);
    

    应该是:

    $(".presentimg").attr('src', miniimgrc3);
    

    更新小提琴: http://jsfiddle.net/nv9em/

    此外,您可以将代码缩短为只有一个事件处理程序:

    $(".imgcontainer").each(function() {
        var imgsrc = $(".minicontainer img:first-child").attr("src");
        $(this).append('<img src="' + imgsrc + '" class="presentimg"/>');
    });
    
    $(".miniimg, .miniimg2, .miniimg3").click(function() {
        var miniimgrc = $(this).attr("src");
        $(".presentimg").attr('src', miniimgrc);
    });
    

    更新小提琴: http://jsfiddle.net/Fr5yW/

    【讨论】:

    • 这很尴尬:/对不起。
    • @Fiddler:没问题,有时只需要第二双眼睛:)。我也有一个关于如何让它更短的建议
    • 非常感谢,但我有另一个问题,我一直在尝试使用每个,但它似乎不起作用jsfiddle.net/nv9em/1
    • @Fiddler:你需要根据被点击的小img来确定正确的img.presentImgjsfiddle.net/aFNjV
    • 有什么方法可以避免每个 .img 容器的 .presentimg 与页面上的 .miniimg 具有相同的 src
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    相关资源
    最近更新 更多