嗨,我正在编写一个脚本来从一些 json 读取数据
我想做几件事:
循环遍历数据并添加新<divs>
的包含来自 json 的数据
我想每行有 3 个项目
这是我第一次尝试使用这种将 div 添加到要生成行的 dom 的方法(我附加的 json 示例数据只有 1 个条目)我的预期 html 结构如下:(relatedDetails 和相关的标题 div页面上已经存在。
<div class="relatedDetails">
<div class="relatedHeader">Unit Bases near by:</div>
<div class="detailRow">
<div class="relatedItem">
<img class="relatedImage" src=""/>
<div class="relatedTitle">Title</div>
</div>
<div class="relatedItem">
<img class="relatedImage" src=""/>
<div class="relatedTitle">Title</div>
</div>
<div class="relatedItem">
<img class="relatedImage" src=""/>
<div class="relatedTitle">Title</div>
</div>
</div>
<div class="detailRow">
<div class="relatedItem">
<img class="relatedImage" src=""/>
<div class="relatedTitle">Title</div>
</div>
<div class="relatedItem">
<img class="relatedImage" src=""/>
<div class="relatedTitle">Title</div>
</div>
<div class="relatedItem">
<img class="relatedImage" src=""/>
<div class="relatedTitle">Title</div>
</div>
</div>
</div>
我的 json 看起来像这样:
[{"id":"5","slug":"boston-manor-park-car-park","name":"Boston Manor Park car park","image":"","pinType":"ub","addr":"Boston Manor Road, London ","lat":"51.48967509541307","lng":"-0.3164195004638941","contact":"Reel Film Locations: ","restrictions":"Shared use with park users. External features unavaliable at present"}]
我已经编写了一些 jquery 来解析这些数据并创建上述结构,但它没有将 div 添加到 dom。
不确定它是否与我如何使用变量来访问类有关,所以我知道<divs>
我也想附加哪一行/相关项目,或者其他什么。
我的jQuery如下:
function createRelated(myRelated){
alert('create related')
console.log(myRelated);
var relCount = 0;
var rowCount = 0;
var itemCount = 0;
$.each(myRelated, function() {
if(relCount == 3){
relCount = 0;
};
// create a new row
if(relCount = 0){
var rowClass = 'relRow'+rowCount;
$("<div/>",{
"class": "detailRow "+rowClass
}).appendTo( ".relatedDetails" );
rowCount++;
}
// create a new related item div
var itemClass = 'item'+itemCount;
$("<div/>",{
"class": "relatedItem "+itemClass,
}).appendTo(rowClass);
//add the data to the related item
$(itemClass).data('location',this);
//add item to to our row
$(rowClass).append(itemClass);
// now loop through the keys and values and add the data
$.each(this, function(k, v) {
//add divs to the related item div
});
itemCount++;
relCount++;
});
};
测试页面:http: //2012.reelfilmlocations.co.uk/Modules/builder_areaLocs.php
* 更新* 我在这里创建了一个 js 小提琴:http: //jsfiddle.net/DizzyHigh/35Jrc/2/
divs sinpmy 没有被创建,我不知道为什么:(