我有一个网页,显示一系列世界领导人的图像。
我需要添加一个按钮,在该阵列上添加一个额外的引线并显示它 如果有人能指出我正确的方向,请提前感谢。
<button class="btn" id="addLeader">Add Leader</button>
</section>
<script type="text/javascript">
window.onload = function () {
var ArrayOfImages = ['images/trump.jpg', 'images/putin.jpg', 'images/merkel.jpg', 'images/jinping.jpg']; //array of images
ArrayOfImages.forEach(function (image) { // for each link l in ArrayOfImages
var img = document.createElement('img'); // create an img element
img.src = image; // set its src to the link l
img.height = '300';
img.width = '200';
img.hspace = '20';
document.body.appendChild(img); // append it to the body
});
var addButton = document.getElementById('addLeader');
addButton.addEventListener('click', addLeader);
}
function addLeader(){
ArrayOfImages.push('images/kimjongun.jpg');
console.log(ArrayOfImages);
}
</script>
答案 0 :(得分:1)
如果将显示部件转换为功能,可以调用它来重新渲染。我做了一个简单而天真的版本。
var ArrayOfImages = ['images/trump.jpg', 'images/putin.jpg', 'images/merkel.jpg', 'images/jinping.jpg']; //array of images
function displayImages (images) {
images.forEach(function (image) { // for each link l in ArrayOfImages
var img = document.createElement('img'); // create an img element
img.src = image; // set its src to the link l
img.height = '300';
img.width = '200';
img.hspace = '20';
document.body.appendChild(img); // append it to the body
});
}
var addButton = document.getElementById('addLeader');
addButton.addEventListener('click', addLeader);
displayImages(ArrayOfImages);
function addLeader(){
ArrayOfImages.push('images/kimjongun.jpg');
document.body.innerHTML = ''; //clear previous images
displayImages(ArrayOfImages);
}