我正在从下面的代码生成列表中的项目。为了让它正确显示,我需要创建一个 html 字符串。此列表中的每个项目都应该成为一个超链接,您单击它,它就会使用新数据重新加载页面,因此我需要保存每个项目的 ID,以便检索该项目的正确数据 对我来说,完成我想要完成的任务的最佳方法是什么?
$(r.campuses).each(function(index, item) {
if (item.campusID != 55) {
var HTMLcontent = '<div class="ml-32 mt-16 mb"><a class="other-school"><label class="other-schools-list">' +
item.campusName + '</label></a><br /></div>';
$('.group').append(HTMLcontent);
}
});
最佳答案
我不确定这是否是您所需要的,但看起来您想将 item.campusID
在 href
您的a
的属性元素。
更新
在代码中添加点击监听器以处理用户点击链接。
你可以这样做:
$(r.campuses).each(function(index, item) {
if (item.campusID != 55) {
var HTMLcontent = '<div class="ml-32 mt-16 mb"><a href="path/to/your/' + item.campusID + '" class="other-school"><label class="other-schools-list">' + item.campusName + '</label></a><br /></div>';
$(HTMLcontent).on('click', function() {
window.location.href = window.location.href + "?id=" + item.campusID;
});
$('.group').append(HTMLcontent);
}
});
只需更改 path/to/your/
走向正确的道路。
关于javascript - 保存循环中每个项目的 ID,以便可以将其用作超链接,Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55210674/