我在内存中创建一个 div:
var video_div = document.createElement('div');
video_div.className = "vidinfo-inline";
本质上我有一些变量:
var key = "data-video-srcs";
var value = '{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}';
我使用 jquery 将该数据属性添加到 div:
$(video_div).attr(key, value);
这是我的问题。这样做之后我得到了这个:
<div class="vidinfo-inline" data-video-srcs="{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}"></div>
将 json 放在那里是行不通的。它必须用单引号引起来。它必须看起来像这样:
<div class="vidinfo-inline" data-video-srcs='{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}'></div>
稍后我会做这样的事情:
var video_srcs = $('.vidinfo-inline').data('video-srcs');
除非 json 包含在单引号中,否则这将不起作用。
有人有什么想法吗?
编辑:
根据jquery:http://api.jquery.com/data/#data-html5
When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string.
因此我无法转义双引号,它必须位于单引号内。我有一个解决方法,除非其他人有更好的答案,否则我会将其发布为答案。
最佳答案
我有一个解决方法。如果有人有更好的解决方案,我很乐意看到。
我写了一个替换方法:
var fixJson = function(str) {
return String(str)
.replace(/"{/g, "'{")
.replace(/}"/g, "}'");
};
所以基本上我将 html 发送到这个函数中并将其插入到 DOM 中。
例如:
var html = htmlUnescape($('#temp_container').html());
html = fixJson(html);
我意识到这有一些代码味道。我的意思是,只是为了将双引号修复为单引号而遍历该元素上的所有内容,这很糟糕。但由于缺乏其他选择或想法,它仍然有效。 :\
关于javascript - 如何强制 jquery attr() 添加带有单引号的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18579528/