简体   繁体   English

为多个 img 标签更改 hover 上的 img src 属性

[英]Change img src attribute on hover for multiple img tags

I wonder if anyone can help??请问有没有人可以帮忙?? It's been a while since I've been on here so hope somebody can give me some pointers as I have hit a mental block!自从我来到这里已经有一段时间了,所以希望有人能给我一些指示,因为我遇到了精神障碍!

I'm trying to change the src attribute for an image on hover which might not sound too difficult but I'm trying to do it for a number of components and write a function that will take care of them all at once so I don't have to repeat code!我正在尝试更改 hover 上图像的 src 属性,这听起来可能不太难,但我正在尝试为许多组件执行此操作并编写一个 function 来一次处理所有这些,所以我不不必重复代码!

I have done a fair bit of digging and in my head, this seems to make the most sense but it's not working?我已经进行了相当多的挖掘,在我的脑海中,这似乎最有意义,但它不起作用? Can anyone see where I'm going wrong??谁能看到我哪里出错了??

 $(function(){ $('img.natcard-img').each(function() { var image=$('img',this), offPng=image.attr('src'), onPng=offPng.replace(/-one\.(\w+)$/,'-two.$1'); onImg=new Image(); onImg.src=onPng; $(this).hover( function(){image.attr('src',onPng)}, function(){image.attr('src',offPng)} ) }); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img src="https://via.placeholder.com/140x100" alt="example 1" class="natcard-img">

From above, I'm using a naming convention for the images that should make it an easier swap ie.从上面看,我对图像使用了一个命名约定,应该使它更容易交换,即。 just amend the filename slightly in each case and I believe this should work on any file type jpg/png.在每种情况下只需稍微修改文件名,我相信这应该适用于任何文件类型 jpg/png。

Many thanks for any pointers!非常感谢您的指点!

I tested it on my computer.我在我的电脑上测试了它。 In the console I had this error:在控制台中我有这个错误:

jquery-3.5.1.slim.min.js:2 Uncaught TypeError: Cannot read property 'replace' of undefined

I solved it by fixing the selector, replacing:我通过修复选择器来解决它,替换:

var image=$('img',this),

With this:有了这个:

var image=$(this),

Inside $(...).each(function() {... }) , this is a DOM node, and you just need to wrap it with $() to get a jQuery object.$(...).each(function() {... })里面, this是一个 DOM 节点,你只需要用$()包裹它就可以得到 jQuery object。

Just change var image=$('img',this) to:只需将var image=$('img',this)更改为:

var image=$(this)

What yours is doing is looking for an img that is a child of the current one...which is not a real scenario你正在做的是寻找一个 img 是当前 img 的孩子......这不是真实的场景

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM