javascript - 将 id 分配给从 JSON 文件动态创建的 div

标签 javascript jquery html

我想将动态 id 属性分配给通过 JavaScript 附加的 div。例如:

function x() {
    for (current_list = 0; current_list < data.length; current_list++) {
        $("#current").append(
            "<div class="card">" +
            "<a href="" + data[current_list].url + "">" + data[current_list].name + "</a>" +
            "</div>");
    }
}

将附加两张卡片,所以我想为它们分配一个 id,如果 JSON 中存在更多数量的数组,它会增加。

最佳答案

你可能正在寻找这个。

function x() {
  var container=$("#current");
  for(var i=1;i<10;i++)
  {
    var id="card"+i;
    var divHtml="<div class='"+id+"'>" +
      "<a href=""+data[current_list].url+"">"+data[current_list].name+"</a>" +
    "</div>"
    container.append(divHtml);
   }
}

关于javascript - 将 id 分配给从 JSON 文件动态创建的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53390757/

相关文章:

javascript - Jquery 查找多个匹配项

javascript - 什么是 var x = x || {} ;

javascript - 使用jquery步骤,我们如何直接加载最后一步

javascript - 高亮显示 div onclick

jQuery 动态调整元素及其内容 onClick

JavaScript 正则表达式 : How to split html string into array of html elements and text nodes?

html - 当宽度>100% 时,如何在 flexbox 中居中放置一个 div?

javascript - 用时刻 js 实现的计数器计数

javascript - jQuery/JavaScript : Click event on a checkbox and the 'checked' attribute

html - IE 7 将我的水平导航栏变成双线