j查询更新图像 src 在悬停时

jQuery update image src on hover

本文关键字:悬停 src 图像 查询 更新      更新时间:2023-09-26

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

例如:这是 HTML法典:

<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>

然后,添加事件侦听器:

法典:

// 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 中。

.tip已经是图像,因此您无法找到带有$(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()

var elem = $(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.attr('data-original'));
});

或者保持原样,不要寻找图像

$('.tip').hover(function()
{
   var elem = $(this);
   // set the 'src' to the 'data-original' value
   elem.attr('src', elem.attr('data-original'));
});

您已将悬停绑定到 img 元素,因此找不到 img 子元素。只需使用它,或将悬停更改为.tip_trigger。

$('.tip_trigger').hover(function() // That should do the trick
{
   // 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'));
});

jQuery.find() 搜索子项。您已经找到了带有".tip"选择器的img。

var elem = $(this);