Javascript:在HTML中转义双引号

栏目: Html · 发布时间: 5年前

内容简介:翻译自:https://stackoverflow.com/questions/4475306/javascript-escaping-double-quotes-in-html
如果它包含双引号,我如何防止图像[i] .title破坏HTML?
for ( i=0;i<=images.length-1;i++ ){
    gallery += '<img width="250" height="250" src="' +  images[i].src + '" title="' + images[i].title + '" />';
}
您可以使用 replace()

方法来转义双引号:

for (var i = 0; i < images.length; ++i) {
    gallery += '<img width="250" height="250" src="' + images[i].src
        + '" title="' + images[i].title.replace(/\"/g, '\\"') + '" />';
}

编辑:结果将是一个有效的Javascript字符串,但不会作为HTML标记工作,因为HTML解析器不理解反斜杠转义.您必须在图像标题中用单引号替换双引号字符:

for (var i = 0; i < images.length; ++i) {
    gallery += '<img width="250" height="250" src="' + images[i].src
        + '" title="' + images[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 + "' />";
}

翻译自:https://stackoverflow.com/questions/4475306/javascript-escaping-double-quotes-in-html


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Lighttpd

Lighttpd

Andre Bogus / Packt Publishing / 2008-10 / 39.99

This is your fast guide to getting started and getting inside the Lighttpd web server. Written from a developer's perspective, this book helps you understand Lighttpd, and get it set up as securely an......一起来看看 《Lighttpd》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具