【问题标题】:Replce img src using Jquery使用 Jquery 替换 img src
【发布时间】:2019-04-27 05:06:29
【问题描述】:

我正在尝试使用 jquery(使用 MOBILE 发布)在悬停时更改 img src 的一部分。这是html代码

<a onclick="slideshow(7); return false;"href="http://example.com/12345">
<img src="https://DEF.com/123-post.jpg" width="200" heigh="200" class="fish" id="thumbnail_5">
</a>

这里是jquery

$('a img').hover (function(){
    this.src = this.src.replace('post','mobile');
});

也许我做错了什么。请帮帮我

【问题讨论】:

  • 试试类似的东西。首先将现有的 src 字符串保存在变量中,然后替换所需的字符串,然后将更改后的字符串重新分配给 src 属性。还要设置属性使用$(this).prop('src')$(this).prop('src',myVar) 设置属性
  • 为什么要更改第一个代码?我的代码在 sn-p 中正常工作,但如果对您不起作用,请检查控制台是否有错误。域DEF.com 也不安全,浏览器不会从中下载图像,导致hover 事件在几秒钟内没有触发。

标签: jquery image replace hover src


【解决方案1】:

您应该将新字符串放在String.replace() 的第二个参数中,而不是使用两次。

$('a img').hover(function(){
  this.src = this.src.replace('post', 'mobile');
});

$('a img').hover(function(){
  this.src = this.src.replace('post', 'mobile');
  console.log(this.src);
});
img {
  width: 100px;
  height: 100px;
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://example.com/12345">
  <img src="http://aDEF.com/123-post.jpg" width="200" heigh="200" class="fish" id="thumbnail_5">
</a>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    相关资源
    最近更新 更多