我正在尝试获取一个图像名称并替换它。从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"));
});这将返回错误:Cannot read property 'replace' of undefined
只是比较一下,下面这个不起作用的脚本是我使用的一个类似的脚本,它工作得很好:
<!-- 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"));
});为什么脚本不起作用?两个类似的脚本,一个可以工作,一个不能工作。我甚至尝试过在stackoverflow中提到的here,但它仍然存在同样的问题。
发布于 2020-05-09 07:39:17
在所示的超文本标记语言中,div对图像使用其style属性。
第二个脚本之所以有效,是因为它替换了img标记的src元素。
因为您试图修改的div没有src属性,所以它是undefined,因此不会响应您尝试调用的方法。
试试这个:
$('#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'));
});发布于 2020-05-09 07:39:24
您正在尝试更改src属性,但没有具有src属性的标记。我在下面添加了一个img标记作为示例。
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<html>
<body>
<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); width:150px; height:100px;">
content
</div>
Image tag with src attribute:
<br>
<img id="myImg" src='https://img.youtube.com/vi/iBy8UdG3VOo/default.jpg' />
</a>
</body>如果要更改样式标签背景,请改为编辑该属性。这应该适用于样式:
$('.related-posts-thumb').each(function() {
console.log('div style'+ $(this).attr("style") )
myBgStyle=$(this).attr("style").replace("default.jpg", "maxresdefault.jpg");
console.log('new bg style: '+myBgStyle)
$(this).attr('style',myBgStyle);
});
mySrc=$('#myImg').attr("src").replace("default.jpg", "maxresdefault.jpg");
console.log('new image source: '+mySrc);
$('#myImg').attr("src", mySrc);请看这里:
发布于 2020-05-09 07:36:55
第二行应该更简单:
$(this).attr("src", "maxresdefault.jpg"));如果您只想将其应用于具有src属性但为"source.jpg“的图像,则应该在选择器中定义它,因此它应该是
$('#main-content #Blog1 article .related-posts .related-content article .related-posts-thumb[src="source.jpg"]').each(function() {
$(this).attr("src", "maxresdefault.jpg"));
});https://stackoverflow.com/questions/61689709
复制相似问题