简体   繁体   English

在循环中的每个项目上保存ID,以便将其用作超链接,jQuery

[英]save ID on each item in loop so it can be used as a hyperlink, Jquery

I am generating items in list from the below code. 我正在从下面的代码生成列表中的项目。 In order for it to display correctly I need to create an html string. 为了使其正确显示,我需要创建一个html字符串。 Each item in this list is supposed to become a hyperlink where you click on it and it reloads the page with new data, so I need to save the ID on each item in order to retrieve the correct data for that item What is the best way for me to do what I am trying to accomplish? 此列表中的每个项目都应成为您单击它的超链接,它会在页面上重新加载新数据,因此我需要在每个项目上保存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);
  }
});

I'm not sure this is what you need but looks like you want to put the item.campusID in the href attribute of your a element. 我不知道这是你需要什么,但看起来你要把item.campusIDhref您的属性a元素。

UPDATE UPDATE

Adding click listener to the code to handle user clicking on the link. 将点击侦听器添加到代码中,以处理用户在链接上的点击。

you can do it like this: 您可以这样做:

$(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);
  }
});

Just change path/to/your/ to your correct path. 只需将path/to/your/更改为正确的路径即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM