我正在尝试构建一个非常基本的图像轮播。我有一系列照片,其中一些将存储在本地,但我希望能够添加来自网络的其他图片。我有它所以单击一个按钮会将用户放入文本框的图像的URL添加到数组中。 URL被添加但是在控制台中,当我检查数组时它不存储URL,而是存储图像#url。如何才能存储URL?谢谢!
var images = ['images/earth.jpg', 'images/shark.jpg', 'images/trolltunga.jpg'];
var blankWarning = document.getElementById("hidden");
var previousButton = document.querySelector('#previousButton');
var nextButton = document.querySelector('#nextButton');
var addImage = document.querySelector('#addImage');
var image = document.querySelector('img');
var url = document.getElementById('url');
var x = 0;
previousButton.addEventListener('click', function() {
x--;
if (x < 0) {
x = (images.length - 1);
}
image.src = images[x];
});
nextButton.addEventListener('click', function() {
x++;
if (x === images.length) {
x = 0;
}
image.src = images[x];
});
addImage.addEventListener('click', function() {
if (url === '') {
blankWarning.style.display = 'inline';
blankWarning.style.color = 'red';
} else {
images.push(url);
}
});
#image-wrapper img {
width: 100px;
height: 100px;
}
#hidden {
display: none;
}
<div id="image-wrapper">
<img src='http://placehold.it/100x100' />
</div>
<div id="button-wrapper">
<button id="previousButton">Previous</button>
<button id="nextButton">Next</button>
</div>
<div id="add-image">
URL: <input type="text" id="url">
<button id="addImage">Add an image</button><br>
<p id="hidden">Image URL field cannot be blank</p>
</div>