jquery - 尝试用 jQuery 替换图像文件名

标签 jquery

我正在尝试获取图像名称并替换它。从 default.jpgmaxresdefault.jpg。但是,我正在使用的脚本会抛出错误,而在我看来它应该可以工作。

HTML:

<a href="https://xxxxxxxxx.html" rel="nofollow" target="_self" title="Sample post with one video, part three">
  <div class="related-posts-thumb" itemprop="thumbnailURL" style="background: url(https://img.youtube.com/vi/iBy8UdG3VOo/default.jpg)"></div>
</a>

jQuery:

<!-- LET'S IMPROVE IMAGE QUALITY OF YOUTUBE THUMBNAILS IN THE RELATED POSTS -->
$('#main-content #Blog1 article .related-posts .related-content article .related-posts-thumb').each(function() {
  $(this).attr("src", $(this).attr("src").replace("default.jpg", "maxresdefault.jpg"));
});

这会返回错误:无法读取未定义的属性“替换”

只是为了进行比较,下面那个不起作用的脚本是我使用的类似脚本,并且运行得很好:

<!-- LET'S IMPROVE IMAGE QUALITY OF AVATARS IN THE COMMENTS -->
$('#main-content #Blog1 article #comments .comment .avatar-image-container img').each(function() {
  $(this).attr("src", $(this).attr("src").replace("s35", "s72"));
});

为什么脚本不起作用?两个相似的脚本,一个有效,另一个无效。我什至尝试了提到的here在 stackoverflow 上,但仍然有同样的问题。

最佳答案

在显示的 HTML 中,div 使用图像的 style 属性。

第二个脚本之所以有效,是因为它替换了 img 标记的 src 元素。

由于您尝试修改的 div 没有 src 属性,因此它是 未定义,因此不会响应您尝试调用的方法。

试试这个:

$('#main-content #Blog1 article .related-posts .related-content article .related-posts-thumb').each(function() {
  $(this).attr('style', $(this).attr('style').replace('default.jpg', 'maxresdefault.jpg'));
});

关于jquery - 尝试用 jQuery 替换图像文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61689709/

相关文章:

jQuery Blur 在 href 之前触发

javascript - 滚动div,固定,再次滚动

javascript - 如何使用 jQuery/Javascript 隐藏 anchor 标记之前的元素?

javascript - 如何创建仅以字符串中的第一个字母或空格后开始的任何其他字母开头的自动完成功能

javascript - 单击jquery中的按钮后如何添加新的选择框

jquery - groupon api - 未获得所有优惠

javascript - jQuery 动画步骤函数

javascript - 悬停时自动滚动图像高于容器

javascript - 表中的 jQuery slideDown 和 SlideUp 看起来不正确

javascript - 让 JQuery 创建多个按钮,这些按钮使用 CSS 在一组中设置样式