jQuery在悬停时更新图像src [英] jQuery update image src on hover

查看:59
本文介绍了jQuery在悬停时更新图像src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想在链接悬停之前加载图片,所以这是脚本,但它不起作用,有人可以帮我纠正吗?
我为每个链接添加了一个事件监听器,并在mouseover上调用了一个设置图像的函数。为了使事情变得更有趣,我们可以在这里复制lazyload并使用data-original属性:)

I don't want the images to load until the link is hovered, so for that here is the script but it's not working, can someone help me in correcting it? I added an event listener to each link, and on mouseover called a function that sets the image. To make things more interesting, we can copy lazyload a bit here and also use the data-original property :)

例如:这是HTML
代码:

For example: this is the HTML Code:

<li>
   <a href="#" class="tip_trigger">
      <img class="tip" alt="300 Grams"
              data-original="https://lh5.googleusom/-qCRpw.../300%2520.jpg"
              src='empty.gif' width="90" height="90"/>
      Alex
   </a>
</li>

然后,添加一个事件监听器:

Then, add an event listener:

代码:

// call for each element with the class 'tip' that's being hovered upon
$('.tip').hover(function()
{
   // retrieve the image inside this element
   var elem = $(this).find('img');

   // set the 'src' to the 'data-original' value
   elem.attr('src', elem.attr('data-original'));
});

对于现场演示,你可以看到这个页面 http://bloghutsbeta.blogspot.com/2012/04/testing-slidernav.html
上述部分脚本仅添加到'A'类别中的第一个字母ALEX。

for a live demo, you can see this page http://bloghutsbeta.blogspot.com/2012/04/testing-slidernav.html the above part of script is only added to the first letter ALEX in 'A' Category.

推荐答案

.tip 已经是图像,因此您无法找到 $(this)的图像.find('img');

.tip is already the image so you cannot find an image with $(this).find('img');

尝试改为

$('.tip_trigger').hover(function()
{
   // retrieve the image inside this element
   var elem = $(this).find('img');

   // set the 'src' to the 'data-original' value
   elem.attr('src', elem.data('original'));
});

还使用 .data()方法代替 .attr()

这篇关于jQuery在悬停时更新图像src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆