2016-10-23 72 views

回答

1

由于[style =]后面的单引号开头在[url(]。 ]处结束,因此字符串已经包含单引号和双引号,因此您必须转义第三个。

变化

你应该将代码从

$(".wrapper").append("<div class='slide bgimage' style='background-image: url('img/" + img + ".jpg');'></div>"); 

改变

$(".wrapper").append("<div class='slide bgimage' style='background-image: url(\"img/" + img + ".jpg\");'></div>"); 

var field = { 
 
\t 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>

0

它不是一个很好的做法,插入该字符串休息/追加像 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); 

希望它可以帮助

1

您可以利用jQuery(html, attributes)。请注意,对于cssurl()函数中的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>

+0

+1,这是去海事组织,但请记住,'class'是保留关键字,并且要经常被引用的方式。 – adeneo

+0

@ adeneo _“,但请记住'class'是一个保留关键字,并且应该始终引用。”_以前有同样的考虑,但已被更正。将尝试找到交换 – guest271314

+0

@ adeneo http://stackoverflow.com/a/36638058/,http://stackoverflow.com/q/4348478/。无论如何,更新的帖子都包含引号。 – guest271314