[英]Include background-image url css in jquery string
How do I include the css style background-image:url('') in a jquery string. 如何在CSS字符串中包含CSS样式background-image:url('')。 This string breaks at the url('
该字符串在url('
var img=field.img;
$(".wrapper").append("<div class='slide bgimage' style='background-image: url('img/" + img + ".jpg');'></div>");
The string breaks because the opening single quotation mark after [style=] ends at [url(]. Since the string already contains both single quotation marks aswell as double quotation marks, you have to escape the 3rd. 因为[style =]之后的单引号结束于[url(]),所以该字符串断裂,因为该字符串既包含单引号又包含双引号,因此必须转义第三个。
Change
更改
You should change the code from 您应该将代码从
$(".wrapper").append("<div class='slide bgimage' style='background-image: url('img/" + img + ".jpg');'></div>");
to 至
$(".wrapper").append("<div class='slide bgimage' style='background-image: url(\"img/" + img + ".jpg\");'></div>");
Example
例
var field = { img: "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/140626_Tierser_Alpl_Rossz%C3%A4hne.jpg/245px-140626_Tierser_Alpl_Rossz%C3%A4hne" } var img=field.img; $(".wrapper").append("<div class='slide bgimage' style='background-image: url(\\"" + img + ".jpg\\");'></div>");
.slide {display:inline-block;width:400px;height:400px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="wrapper"></div>
You can utilize jQuery(html, attributes)
. 您可以利用
jQuery(html, attributes)
。 Note, quotes are not necessary for URL within css
url()
function. 注意,
css
url()
函数中的URL不需要引号。
$(function() { var field = { img: "http://placehold.it/100x100" } var img = field.img; var div = $("<div></div>", { "class": "slide bgimage", "style": "background-image: url(" + img + ")" }); $(".wrapper").append(div); });
.wrapper, .wrapper div { width: 100px; height: 100px; display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <div class="wrapper"></div>
Its not a good practice to insert/append a div element like that you might consider changing into this format 插入/附加div元素(例如您可能会考虑更改为这种格式)不是一个好习惯
var img=field.img;
var imgUrl='img/' + img +'.jpg';
var divElement=jQuery("<div>");
divElement.addClass('slide');
divElement.addClass('bgimage');
divElement.css('background-image',imgUrl);
$(".wrapper").append(divElement);
Hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.