我在网站上有一个如下所示的元素:
<div id="item" style="background-image: url('url to the image')"></div>
现在我需要一个javascript,它只提取此背景图像的网址,并将其替换为存储在var中的网址。
这怎么可能在&#34;整洁&#34;方式:)?
答案 0 :(得分:2)
您可以按id
选择div,然后使用setAttribute
将style
属性设置为包含yourVar
中存储的新网址的字符串,如下所示:
var item = document.getElementById('item');
var newStyle = 'background-image: url(' + yourVar + ');';
item.setAttribute('style', newStyle);
答案 1 :(得分:1)
$('#item').css('background-image', 'url(' + var + ')');