Javascript:在HTML中转义双引号 [英] Javascript: Escaping double quotes in HTML
问题描述
pre> for(i = 0; i< = images.length-1; i ++){
gallery + ='< img width =250height =250 src ='+ images [i] .src +'title ='+ images [i] .title +'/>';
}
您可以使用 replace()方法来转义双引号:
$ b $ (var i = 0; i< images.length; ++ i){
gallery + ='< img width =250height = 250src ='+ images [i] .src
+'title ='+ images [i] .title.replace(/ \/ g,'\\ +'/>';
}
编辑:结果将是一个有效的Javascript字符串,但不能作为HTML标记,因为HTML解析器不明白反斜杠转义。您将不得不在图像标题中用双引号替换双引号字符:
for(var i = 0; i < images.length; ++ i){
/ pre>
gallery + ='< img width =250height =250src ='+ images [i] .src
+' title ='+ image [i] .title.replace(/ \/ g,')+'/>';
}
或反转您的标记中的报价类型:
for(var i = 0; i< images.length; ++ i){
gallery + =< img width ='250'height ='250'src ='+ images [i]。 src
+'title ='+ images [i] .title +'/>;
}
How can I prevent
images[i].title
below from breaking the HTML if it contains double quotes?for ( i=0;i<=images.length-1;i++ ){ gallery += '<img width="250" height="250" src="' + images[i].src + '" title="' + images[i].title + '" />'; }
解决方案You can use the replace() method to escape the double quotes:
for (var i = 0; i < images.length; ++i) { gallery += '<img width="250" height="250" src="' + images[i].src + '" title="' + images[i].title.replace(/\"/g, '\\"') + '" />'; }
EDIT: The result will be a valid Javascript string, but won't work as HTML markup because the HTML parser doesn't understand backslash escapes. You'll either have to replace double quote characters with single quotes in your image title:
for (var i = 0; i < images.length; ++i) { gallery += '<img width="250" height="250" src="' + images[i].src + '" title="' + images[i].title.replace(/\"/g, "'") + '" />'; }
Or invert the quote types in your markup:
for (var i = 0; i < images.length; ++i) { gallery += "<img width='250' height='250' src='" + images[i].src + "' title='" + images[i].title + "' />"; }
这篇关于Javascript:在HTML中转义双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!