如何在HTML属性值中转义引号? [英] How do I escape quotes in HTML attribute values?

查看:153
本文介绍了如何在HTML属性值中转义引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过创建一个html字符串,我构建了一行插入到一个表格中,即

  var row =; 
row + =< tr>;
row + =< td>名称< / td>;
row + =< td>< input value ='+ data.name +'/>< / td>;
row + =< / tr>;

data.name 是从一个可以包含任何字符的ajax调用。如果它包含单引号('),它将通过定义属性值的结尾来破坏HTML。



如何确保字符串在浏览器中正确显示?

解决方案

您只需将任意'字符与相应的HTML实体字符代码进行交换:

  data.name.replace(/'/ g,&#39;); 

或者,您可以使用jQuery的DOM操作方法创建整个事物:

  var row = $(< tr>)。append(< td>名称< / td>< td>< / td> ;); 
$(< input>,{value:data.name})。appendTo(row.children(td:eq(1)));


I'm building up a row to insert in a table using jQuery by creating a html string, i.e.

var row = "";
row += "<tr>";
row += "<td>Name</td>";
row += "<td><input value='"+data.name+"'/></td>";
row += "</tr>";

data.name is a string returned from an ajax call which could contain any characters. If it contains a single quote, ', it will break the HTML by defining the end of the attribute value.

How can I ensure that the string is rendered correctly in the browser?

解决方案

You just need to swap any ' characters with the equivalent HTML entity character code:

data.name.replace(/'/g, "&#39;");

Alternatively, you could create the whole thing using jQuery's DOM manipulation methods:

var row = $("<tr>").append("<td>Name</td><td></td>");
$("<input>", { value: data.name }).appendTo(row.children("td:eq(1)"));

这篇关于如何在HTML属性值中转义引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆