期待:
当您单击 56 个人的脸部图像(请参阅 index.html
)时,可以在弹出窗口/“工具提示”中显示 56 个人中每个人的数据,而无需使用 ID。例如,单击 Allan 的图像应该会显示她存储在 var MLA
中的数据。尝试使用 for 循环但收效甚微,也许是 .each()
示例中有两个 MLA,scripts.js
,但实际上我尝试迭代的项目总共有 56 个。好的,现在我正在获取数组中的最后一个人。
scripts.js(数据,尝试循环)
// MLAs
var MLAs = [
{
"Name": "Nancy Allan",
"Age": 62,
"Constuency": "St. Vital",
"Party": "NDP",
"Gender": "Female",
"Ethnicity": "White"
},
{
"Name": "James Allum",
"Age": null,
"Constuency": "Fort Garry-Riverview",
"Party": "NDP",
"Gender": "Male",
"Ethnicity": "White"
}]
// Shows a popup with MLA information
$(".headshot").click(function(){
$(".tooltip").css("display", "block");
for (i = 0; i < 56; i++) {
$(".tooltipName").html(MLAs[i].Name);
$(".tooltipParty").html(MLAs[i].Party);
$(".tooltipConstuency").html(MLAs[i].Constuency);
$(".tooltipEthnicity").html(MLAs[i].Ethnicity) + ",";
$(".tooltipAge").html(MLAs[i].Age);
}
});
});
使用#ids
并没有真正解决问题,有更好的解决方案吗?
index.html
<img src="assets/img/headshots/allan.jpg" id="0" alt="" class="headshot NDP Female White">
<img src="assets/img/headshots/allum.jpg" id="1" alt="" class="headshot NDP Male White">
<img src="assets/img/headshots/altemeyer.jpg" id="2" alt="" class="headshot NDP Male White">
脚本.js
$(".headshot").click(function(){
index = this.id;
$(".tooltip").css("display", "block");
$(".tooltipName").html(MLAs[index].Name);
$(".tooltipParty").html(MLAs[index].Party);
$(".tooltipConstuency").html(MLAs[index].Constuency);
$(".tooltipEthnicity").html(MLAs[index].Ethnicity); + ","
$(".tooltipAge").html(MLAs[index].Age);
});
});
最佳答案
您不应使用数字 id
属性值。您可以简单地在选择器中使用它们的 .index() 。
<div id="people">
<img src="assets/img/headshots/allan.jpg" alt="" class="headshot NDP Female White">
<img src="assets/img/headshots/allum.jpg" alt="" class="headshot NDP Male White">
...
</div>
-
$(".headshot").on('click', function() {
var idx = $(this).index();
$(".tooltip").css("display", "block");
$(".tooltipName").html(MLAs[idx].Name);
$(".tooltipParty").html(MLAs[idx].Party);
$(".tooltipConstuency").html(MLAs[idx].Constuency);
$(".tooltipEthnicity").html(MLAs[idx].Ethnicity); + ","
$(".tooltipAge").html(MLAs[idx].Age);
});
});
关于javascript - 循环遍历数组时出现问题,避免添加 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28332152/