您好,我正在编写一个脚本来读取某些json的数据
我想做一些事情:
循环遍历数据并添加包含来自json
的数据的新<divs>
我想每行3个项目
这是我第一次尝试使用这种方法将div添加到dom中 我想生成行(我附加的json示例数据只有1个条目) 我想要的html结构如下: (相关详细信息和相关的标题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/
答案 0 :(得分:0)
在示例代码中,您永远不会将()新行追加到文档中。当您完成所有元素的生成后,您需要获得对要将其插入文档的点的引用,并将新元素附加到其中:
$(rowClass).appendTo("#WhereIWantMyData");
你的HTML中有一些你想要插入数据的id =“WhereIWantMyData”的元素。
答案 1 :(得分:0)
if(relCount = 0){
//do stuff
}
应该是
if(relCount == 0){
//do stuff
}