#javascript #jquery #html #json #for-loop
#javascript #jquery #HTML #json #цикл for
Вопрос:
Поскольку в массиве тысячи элементов, я не могу создать iframe
теги для КАЖДОГО элемента (ради загрузки), так как мне сделать так, чтобы в DOM был только один iframe
, но когда вы нажимаете кнопку с именем соответствующего элемента, открывается iframe с соответствующим URL?
Пример:
{
"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>
Как бы я это сделал?
Ответ №1:
Просто измените src
значение одной iframe
динамически созданной кнопки.
// 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>
Ответ №2:
Вы могли бы использовать делегирование событий для #list
, и при нажатии на n-ю кнопку получить доступ к n-му элементу в data
массиве и извлечь соответствующий URL:
const $buttons = $('#list > button');
$('#list').on('click', 'button', function() {
const index = $buttons.index(this);
const { url } = obj.data[index];
$('#url-output').prop('src', url);
});