Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save xcaspar/f76130565666f13b0bb3 to your computer and use it in GitHub Desktop.
Save xcaspar/f76130565666f13b0bb3 to your computer and use it in GitHub Desktop.

JS处理HTML中属性值带双引号的问题

@(Javascript)[转义]

问题

在项目开发中需要从数据库读取数据,然后通过js将数据绑定到一个标签的属性中。例如:
数据库数据: [{“minCount”: 1, “maxCount”: 100,”discount”: 9}]

我定义一个变量,将上面的数据赋值给它:var rule = [{“minCount”: 1, “maxCount”: 100,”discount”: 9}] 在JS中 我将上面的数据添加到一个标签的属性值中:

$(‘.goods’).find(‘select option:selected’).attr(‘data-rule’, rule);

执行完成后去查看前台页面数据,发现变成如下形式:

<option selected=”selected” data-rule=”[{“minCount”: 1, “maxCount”: 100,”discount”: 9}]”></option>

我在用js读取这个属性值得到的却是: [{
截取了前两个引号所引的字符,很明显这不是想要的。

解决方式

双引号传到HTML中要转义,先将数据进行转义替换,代码如下:

 rule.replace(/\”/g, “&quot;”)

在将 rule的值传入属性中,虽然前台看到的还是

<option selected=”selected” data-rule=”[{“minCount”: 1, “maxCount”: 100,”discount”: 9}]”></option>

这种形式,但是你再取data-rule值时,能得到和数据库一样的数据,即: [{“minCount”: 1, “maxCount”: 100,”discount”: 9}]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment