我希望能够根据范围获取数组的元素。
例如:索引0到4和5到6的元素。
这个想法是我在jquery中创建一个带有foreach的数组,我希望能够为0到4的元素添加CSS样式,并从5到6添加另一个样式。
我把我的代码放在一边,这样他们就可以更好地理解这个方法了:
var data = [{
"dataEarth": [{
"qty": 7,
"dataPerson": [{
"name": "Max",
"lastName": "CavaniCaracterística",
"descripcion": "Lorem ipsum lorem ipsum doloretitieisorieo"
}, {
"name": "Max",
"lastName": "CavaniCaracterística",
"descripcion": "Lorem ipsum lorem ipsum doloretitieisorieo"
}, {
"name": "Max",
"lastName": "CavaniCaracterística",
"descripcion": "Lorem ipsum lorem ipsum doloretitieisorieo"
}, {
"name": "Max",
"lastName": "CavaniCaracterística",
"descripcion": "Lorem ipsum lorem ipsum doloretitieisorieo"
}, {
"name": "Max",
"lastName": "CavaniCaracterística",
"descripcion": "Lorem ipsum lorem ipsum doloretitieisorieo"
}, {
"name": "Max",
"lastName": "CavaniCaracterística",
"descripcion": "Lorem ipsum lorem ipsum doloretitieisorieo"
}, {
"name": "Max",
"lastName": "CavaniCaracterística",
"descripcion": "Lorem ipsum lorem ipsum doloretitieisorieo"
}]
}]
}]
var html = "";
$.each(data, function (index, element){
$.each(element.dataEarth, function (index,data) {
console.log(data);
//if the range is 0 to 5 append this
//html += "<div class='firstClass'><p><strong>Pos. 0 to 5</strong></p></div>";
//Else if the range is 6 to 7 append this
//html += "<div class='otherClass'><p><strong>Pos. 6 to 7</strong></p></div>";
});
});
//$(".json_content").html(html);
<div class="json_content"></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.js"></script>
答案 0 :(得分:1)
你的意思是这样的:
var data = [{
"dataEarth": [{
"qty": 7,
"dataPerson": [{
"name": "Max",
"lastName": "CavaniCaracterística",
"descripcion": "Lorem ipsum lorem ipsum doloretitieisorieo"
}, {
"name": "Max",
"lastName": "CavaniCaracterística",
"descripcion": "Lorem ipsum lorem ipsum doloretitieisorieo"
}, {
"name": "Max",
"lastName": "CavaniCaracterística",
"descripcion": "Lorem ipsum lorem ipsum doloretitieisorieo"
}, {
"name": "Max",
"lastName": "CavaniCaracterística",
"descripcion": "Lorem ipsum lorem ipsum doloretitieisorieo"
}, {
"name": "Max",
"lastName": "CavaniCaracterística",
"descripcion": "Lorem ipsum lorem ipsum doloretitieisorieo"
}, {
"name": "Max",
"lastName": "CavaniCaracterística",
"descripcion": "Lorem ipsum lorem ipsum doloretitieisorieo"
}, {
"name": "Max",
"lastName": "CavaniCaracterística",
"descripcion": "Lorem ipsum lorem ipsum doloretitieisorieo"
}]
}]
}]
var html = "";
$.each(data[0].dataEarth[0].dataPerson, function (index,el) {
if (index < 5) {
html += "<div class='firstClass'><p><strong>Pos. 0 to 5</strong></p></div>";
} else {
html += "<div class='otherClass'><p><strong>Pos. 6 to 7</strong></p></div>";
}
});
$(".json_content").html(html);
<div class="json_content"></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.js"></script>