2

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"}';

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>

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');

And that won't work unless the json is in single quotes.

Does anyone have any ideas?

EDIT:

According to 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.

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.

4

2 に答える 2

2

二重引用符を HTML エンティティに置き換えます。

var value = '{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}';

# Naive approach:
value = value.replace('&', '&amp;').replace('"', '&quot;');

# Using jQuery:
var $tmp = jQuery('<div></div>');
value = $tmp.text(value).html();

// Then store it as normal
于 2013-09-02T19:19:21.740 に答える