如何强制jquery attr()添加带有单引号的属性 [英] how to force jquery attr() to add the attribute with single quotes
问题描述
我在内存div中创建了一个
I create an in memory div:
var video_div = document.createElement('div');
video_div.className = "vidinfo-inline";
从本质上讲,我有一些变量:
In essence I have some variables:
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:
And I use jquery to add that data attribute to the div:
$(video_div).attr(key, value);
这是我的问题.这样做之后,我得到了:
Here is my problem. After doing that I get this:
<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放在那里是行不通的.它必须用单引号引起来.它必须看起来像这样:
And that doesn't work putting that json in there. It has to be in single quotes. It has to look like this:
<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>
稍后,我将执行以下操作:
As later on I do something like this:
var video_srcs = $('.vidinfo-inline').data('video-srcs');
除非json用单引号引起来,否则这是行不通的.
And that won't work unless the json is in single quotes.
有人有什么想法吗?
根据jquery: http://api.jquery.com/data/#data- html5
当data属性是一个对象(以"{"开始)或数组(以"["开始)时,则使用jQuery.parseJSON来解析字符串;它必须遵循有效的JSON语法,包括带引号的属性名称.如果该值不能作为JavaScript值解析,则将其保留为字符串.
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.
因此,我无法转义双引号,它必须在单引号内.我有一个解决方法,除非有其他人有更好的答案,否则我将其发布为答案.
Thus I can't escape the double quotes, it has to be inside single quotes. I have a work around and I'll post that as an answer unless someone else has a better answer.
推荐答案
我有一种解决方法.而且,如果有人有更好的解决方案,我很乐意看到它.
I have a workaround. And if anyone has a better solution, I'd love to see it.
我写了一个替换方法:
var fixJson = function(str) {
return String(str)
.replace(/"{/g, "'{")
.replace(/}"/g, "}'");
};
因此,基本上,我将html发送到此函数中并将其插入DOM.
So basically I send the html into this function and insert it into the DOM.
例如:
var html = htmlUnescape($('#temp_container').html());
html = fixJson(html);
我意识到上面有一些代码味道.我的意思是,遍历该元素上的所有内容只是为了将双引号固定为单引号臭味.但是由于缺乏其他选择或想法,它可以工作. :\
I realize that has some code smell to it. I mean, going through everything on that element just to fix the double quotes to single quotes stinks. But for lack of other options or ideas, it works. :\
这篇关于如何强制jquery attr()添加带有单引号的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!