由于数组中有数千个项目,我无法为每个项目创建 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>
<小时/>
我该怎么做?
最佳答案
只需让动态创建的按钮更改一个 iframe
的 src
即可。
// 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/