Reputation: 2235
I have a web service that returns an array of image URLs to me. I want to take these URLs construct a an array of html image tags out of them and then store that array in a data attribute to be called on later. Here's how it looks in the element I store it in. This <a>
would be part of an unordered list <ul>
<a data-path='["<img src="pics/portrait-0.png">","<img src="pics/portrait-1.png">","<img src="pics/portrait-2.png">"]' href="#">Item 1</a>
When I go to retrieve the new elements I'm running the following code below. The image tags are getting passed into a jQuery plugin called Cycle2. The code below is breaking when it hits the 'JSON.parse()' with an unknown token error. Is the content in 'data-path' structured in- correctly? Is there a better approach to doing this?
var onSelect = function(e) {
var data;
data = e.target.getAttribute('data-path');
var pages = JSON.parse(data);
for (var i = 0; i < pages.length; i++) {
display.cycle('add', pages[i]);
}
};
Upvotes: 0
Views: 968
Reputation: 1920
I think it is cleaner saving only the images path on the data-attribute:
<a data-path='["pics/portrait-0.png", "pics/portrait-1.png","pics/portrait-2.png"]' href="#">Item 1</a>
And then create an <img>
object using jQuery:
var onSelect = function(e) {
var data;
data = e.target.getAttribute('data-path');
var pages = JSON.parse(data);
for (var i = 0; i < pages.length; i++) {
display.cycle('add', $('<img/>').attr('src', pages[i]));
}
};
Upvotes: 3
Reputation: 40413
If that's the actual HTML, then your problem is just that you're not escaping your quotes inside the strings:
<a data-path='["<img src=\"pics/portrait-0.png\">", "<img src=\"pics/portrait-1.png\">", "<img src=\"pics/portrait-2.png\">"]' href="#">Item 1</a>
But just because this is confusing to look at, I would probably recommend exploring cleaner alternatives, like storing these in a regular javascript variable instead of trying to mix HTML and JSON content together - whenever you mix things like this, you have to deal with combinations of quotation marks, escape charaters, etc., and it would be easier just to have plain old strings in variables, instead of trying to figure out exactly how to format and parse everything.
Upvotes: 1