javascript - 我有一个包含数千个带有 URL 属性的项目的数组。如何为数组中的每个项目创建一个按钮,以打开 URL 的 iframe?

标签 javascript jquery html json for-loop

由于数组中有数千个项目,我无法为每个项目创建 iframe 标记(为了加载),那么如何才能做到只有一个 iframe 在 DOM 中,但是当您按下具有相应项目名称的按钮时,会打开具有相应 URL 的 iframe?

<小时/>

例如:

{
  "data": [
    {
      "name": "Thomas Jefferson",
      "url": "https://thomas-jefferson.com"
    }
    // Insert a few thousand more objects with the same format
  ]
}

为数组中的每个项目生成一个按钮:

for (var i=0; i < data.length; i++) {
  var item = "<button>" + data[i].name + "</button>";
  $('#list').append(item)
}

DOM 看起来像这样:

<div id="list"></div>

<iframe id="url-output"></iframe>
<小时/>

我该怎么做?

最佳答案

只需让动态创建的按钮更改一个 iframesrc 即可。

// You need to assign an identifier to the object
let obj = {
  "data": [
    {
      "name": "Example.com",
      "url": "https://www.example.com"
    },
    {
      "name": "TTS",
      "url": "https://techtrainsolutions.com"
    }    
    // Insert a few thousand more objects with the same format
  ]
}

// Use let for block scope and avoid the classic closure in a loop problem
for (let i=0; i < obj.data.length; i++) {
  var item = document.createElement("button");
  item.textContent = obj.data[i].name;
  // Set up event handler for the new button
  item.addEventListener("click", function(){
    $("iframe")[0].src = obj.data[i].url; // Point to correct URL
  });
  $('#list').append(item)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list"></div>
<iframe id="url-output"></iframe>

关于javascript - 我有一个包含数千个带有 URL 属性的项目的数组。如何为数组中的每个项目创建一个按钮,以打开 URL 的 iframe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55839796/

相关文章:

jquery - 选择 DIV 但不选择其中的链接,jQuery 问题

javascript - Moment.js - 将本地月份名称翻译成 en-gb

javascript - 如何暂停/恢复/延迟 for 循环?

javascript - 显示多行通知

javascript - 删除特定行中的先前单元格并在 Java 脚本中创建新单元格

javascript - 我可以使用 Javascript 将不可调整大小的现有浏览器窗口更改为可调整大小吗?

javascript - jQuery 获取 DOM 元素的方法

javascript - 如何按其他数组对数组进行排序

javascript - 使用 jquery 切换 LinkBut​​ton 的启用/禁用状态

NANP 电话号码的 jQuery 验证