这是来自html的标签。
<div class="ytp-thumbnail-overlay ytp-cued-thumbnail-overlay" data-layer="4" style="background-image: url("https://i.ytimg.com/vi_webp/VV5oVYVGfNc/sddefault.webp");">我想要做的是:
var bg = $(".ytp-cued-thumbnail-overlay").css('background-image');
bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')
$("#img1").attr('src','bg');我希望使用jQuery将background-image属性放入我的#img src中,但不能替换url("和");
发布于 2016-08-04 21:39:49
不需要替换字符串中所有不需要的部分,只需使用regex来获取所需的部分即可。这将更有效地使用正则表达式,因为您不需要对源字符串进行任何假设,也不需要在设置属性之前进行任何其他修改。这是您需要的所有代码:
string = $(".ytp-cued-thumbnail-overlay").css('background-image');
$("#img1").attr('src', string.match(/.*url\(['|"]([^)]*)['|"]\)/i));下面是一个演示(使用相同的正则表达式,但使用不同的代码来更好地说明该过程):
string = $("#source").text();
$("#match").text(string.match(/.*url\(['|"]([^)]*)['|"]\)/i)[1]);#source, #match { display:inline-block;border:1px solid #aaa;padding:10px; }
#source:before { color:#aaa;content:'source: '; }
#match:before { color:#aaa;content:'match: ';}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="source">url("this is your URL")</div>
→
<div id="match"></div>
为什么匹配优于修改字符串
与将获得css()返回的任何值的方法相比,如果没有找到匹配项,则返回null,您可以在实现中检查它。例如,如果你的背景图像值是http://www.example.com,并且你切掉了前五个和后两个字符,你希望它实际上是url("http://www.example.com/img.png"),你将得到//www.example.c,这不是一个很好的网址。
发布于 2016-08-04 21:30:45
这对我很有效。将bg中的撇号(‘)替换为'bg’
var bg = $(".ytp-cued-thumbnail-overlay").css('background-image');
bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')
$("#img1").attr('src',bg);<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ytp-thumbnail-overlay ytp-cued-thumbnail-overlay" data-layer="4" style="height:200px;background-image: url("https://i.ytimg.com/vi_webp/VV5oVYVGfNc/sddefault.webp");">
</div>
<img id="img1">
发布于 2016-08-04 21:37:44
如果您可以编辑div的超文本标记语言,请使用'而不是"。变化
<div class="ytp-thumbnail-overlay ytp-cued-thumbnail-overlay" data-layer="4" style="background-image: url("https://i.ytimg.com/vi_webp/VV5oVYVGfNc/sddefault.webp");">至
<div class="ytp-thumbnail-overlay ytp-cued-thumbnail-overlay" data-layer="4" style="background-image: url('https://i.ytimg.com/vi_webp/VV5oVYVGfNc/sddefault.webp');">注意: bg是一个变量,不应该用引号括起来。
$(function() {
var bg = $(".ytp-cued-thumbnail-overlay").css('background-image');
bg = bg.substring(5).slice(0, -2);
$("#img1").attr('src', bg);
console.log(bg);
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ytp-thumbnail-overlay ytp-cued-thumbnail-overlay" data-layer="4" style="background-image: url('https://i.ytimg.com/vi_webp/VV5oVYVGfNc/sddefault.webp');">
https://stackoverflow.com/questions/38768624
复制相似问题