html 属性中的引号被标记为 ”来自元素.html()的结果

Quotes in html attributes getting marked up as " in result from element.html()

本文关键字:html 元素 结果 属性 记为      更新时间:2023-09-26

我有以下html:

<div id="ma-uitemplates-container">
    <button id="ExecuteAbort" 
        type="button" 
        class="btn btn-default" 
        data-mistro-command="Execute" 
        data-mistro-events='[{"SE":"click","MEM":[{"MEC":"NotificationManager","ME":"DismissNotification"}]}]'>
        Yes
    </button>
</div>

属性 data-mistro-events 包含一些我在代码中提取并解析为对象的 JSON 数据。

我现在正在编写一些代码,将一些标记从 html 页面保存到数据库中作为模板。

当我使用 jquery 获取此 html 时:

$('#ma-uitemplates-container').html();

它给出以下结果:

<button id="ExecuteAbort" type="button" class="btn btn-default" data-mistro-command="Execute" data-mistro-events="[{&quot;SE&quot;:&quot;click&quot;,&quot;MEM&quot;:[{&quot;MEC&quot;:&quot;NotificationManager&quot;,&quot;ME&quot;:&quot;DismissNotification&quot;}]}]">
    Yes
</button>
您可以看到 jquery 已将我在属性 data-mistro-events='' 上的单引号转换为双引号

data-mistro-events=",然后将属性值中的所有双引号转换为 ".

我怎样才能让它不这样做,而是按照我在页面中编写的方式编写 html?

问候

斯科特

用单引号编写 html 标签属性是无效的,这就是为什么浏览器用双引号转换你的数据错误事件属性并且你的 html 被破坏了。您必须使用带有双引号 (") 而不是单引号 (') 的 html 属性,并使用单引号编写 json。

尝试以下,这将正常工作

<div id="ma-uitemplates-container">
  <button id="ExecuteAbort" 
    type="button" 
    class="btn btn-default" 
    data-mistro-command="Execute" 
    data-mistro-events="[{'SE':'click','MEM':[{'MEC':'NotificationManager','ME':'DismissNotification'}]}]">
    Yes
  </button>
</div>