我正在尝试获取图像名称并替换它。从 default.jpg
到 maxresdefault.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/