【问题标题】:jquery change all src to reljquery将所有src更改为rel
【发布时间】:2014-06-08 21:39:50
【问题描述】:

我试图将鼠标悬停在一张图片上,然后让所有图片变成我正在悬停的一张图片。我已经完成了。

当我鼠标悬停时,我希望图像恢复正常,但我无法弄清楚。

我正在尝试使用 rel 选择器,但在我现在的解决方案中,当我将鼠标移出时,所有图像都会采用第一张图像的 rel 而不是一切都恢复正常。

这是我的 HTML

<div id="container">
        <header id="masthead"><h1>Swap All</h1></header>
        <div id="stage">
            <div id="gallery">
                <img class="photo" rel="_images/image1.jpeg"  src="_images/image1.jpeg"  />
                <img class="photo" rel="_images/image2.jpeg"  src="_images/image2.jpeg"   />
                <img class="photo" rel="_images/image3.jpeg"  src="_images/image3.jpeg"   />


        </div>

这是我的 JS

    function grabIt(){

        var thisImageSrc = this.src;

        $('.photo').attr('src', thisImageSrc);



    }


    function letItGo() {

        var theRel = $('.photo').attr('rel');

        $('#gallery img').attr( 'src', theRel);

        console.log(theRel);
    }


        $('.photo').mouseover(grabIt);
        $('.photo').mouseout(letItGo);

【问题讨论】:

  • 加个jsfiddle链接会更好。
  • 你需要遍历每个img

标签: jquery html image rel


【解决方案1】:

试试这个:

function letItGo() {
    $('#gallery img').each(function() {
        //option#1: pure JS
        this.src = this.rel;
        //option#2: jQuery (I'll leave this in as an option because the OP used this himself and might prefer it even though it is not necessary)
        $(this).attr('src',$(this).attr('rel'));
    });
}

明确一点:您只需要一个选项;如果您想使用纯 JS,请从代码中删除选项#2。反之亦然。


您尝试的方法不起作用,因为您仅将第一张照片的 rel-tag 存储到 var theRel 中。这行var theRel = $('#gallery img').attr('rel');,即使匹配的元素比较多,也只会选择第一个匹配的。

我的代码循环遍历所有匹配的元素,并且对于这些元素中的每一个,它使用自己的 rel-tag 来更改自己的 src-tag,使用 this / $(this)

【讨论】:

  • @BenjaminGruenbaum,实际上只有 jQuery 版本对我有用。你能提供一个纯javascript版本的小提琴吗?也许是因为我使用了 jQuery hover 方法?
猜你喜欢
  • 2014-08-16
  • 1970-01-01
  • 2014-08-21
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
相关资源
最近更新 更多