I have a div that returns an array string:
<div class="overview"><%=getCurrentAttribute('item','item_specs_json','""')%></div>
An array string that looks like this:
[{"k":"type","v":"blue"},{"k":"size","v":"large"}]
I am making a bulleted list from these and there are 25 instances of div.overview per page.
This works but only repeats the first item values for every div. I can't get this to loop each.
Is it possible to do this with what I have?
$(function () {
var specs = $.parseJSON($(".overview").html());
$("div.overview").html('<div class="bullet_spec"></div>');
$.each(specs, function () {
$('div.overview div').append('<ul class="specs"><li class="label">' + this.k + ' : ' + this.v + '</li></ul>');
});
});
I've tried:
$('.overview').each(function () {
and this breaks the script.
Also FYI, when the script breaks the unique values appear on items correctly in the full array string format.
-
1It works, jsfiddle.net/LsAXD/1Ram– Ram2014年01月13日 21:41:21 +00:00Commented Jan 13, 2014 at 21:41
2 Answers 2
If you've got more than one "overview" element, then you'll have to iterate through that list.
$('.overview').each(function() {
var $overview = $(this), specs = $.parseJSON($overview.html());
$overview.html('<div class="bullet_spec"></div>');
$.each(specs, function () {
$overview.children('div').append('<ul class="specs"><li class="label">' + this.k + ' : ' + this.v + '</li></ul>');
});
});
Comments
I'm taking 'I am making a bulleted list from these and there are 25 instances per page' to mean there are 25 .overview, each with there own JSON. You can loop through each, mapping each JSON string to a collection of elements, appending the collection at the end:
$('.overview').each(function(){
var theJSON = JSON.parse(this.innerHTML);
$elems = $.map(theJSON, function(k,v){
return $('<ul class="specs"><li class="label">' + k.k + ' : ' + k.v + '</li></ul>');
});
$spec = $('<div class="bullet_spec"></div>').append($elems);
$(this).html($spec);
});