jquery - 使用 .replace 更改图像源

jquery - change image src with .replace

我有一些图片,当我将鼠标悬停在 div 上时,我想将它们更改为另一张图片。图片 1:"geluid1",图片 2:"geluid2".

$(".block").mouseover(function(){
  $("img",this).attr("src").replace("1","2");
});

但由于某些原因,这似乎无法正常工作。谁能帮我找出问题所在?

您的代码只是获取图像的 src 并替换了内容。但是,它没有更新 img.

src 属性

您没有设置 imgsrc 属性值。使用以下代码将 src 值设置为替换后的值。

$("img",this).attr("src", $('img', this).attr('src').replace("1","2"));

代码

$(".block").mouseover(function() {
    var img = $('img', this); // Cache image object

    img.attr('src', img.attr('src').replace('1', '2'));
    // Update the image src URL to the new URL
});

您需要将要替换的内容放在括号内

$(".block").mouseover(function(){
  var img=$("img",this).attr("src");
  $("img",this).attr("src",img.replace("1","2"));
});