我需要帮助才能得到这个:
<ul id="slides">
<li class="slide">
<img src="url_from_array" />
</li>
<li class="slide">
<img src="url_from_array" />
</li>
</ul>
按输入元素添加图片网址。
我有这段代码
var imgUrl = ['https://i.ytimg.com/vi/m5d1FlSeF-M/maxresdefault.jpg'];
function makeUL(array) {
// Create the list element:
list = document.createElement('ul');
list.id = "slides";
for(var i = 0; i < array.length; i++) {
// Create the list item:
var li = document.createElement('li');
li.className = "slide";
var img = document.createElement('img');
// Set its contents:
img.src = array[i];
li.appendChild(img);
//li.appendChild(document.createTextNode(array[i]));
// Add it to the list:
list.appendChild(li);
}
// Finally, return the constructed list:
return list;
}
// Add the contents of imgUrl to #slides:
document.getElementById('slider').appendChild(makeUL(imgUrl));
function addImg(){
var input = document.getElementById("input");
if (input.value != ""){
imgUrl.push(document.getElementById("input").value);
return list;
}
}
//test obsahu array
var arrayLength = imgUrl.length;
for (var i = 0; i < arrayLength; i++) {
document.getElementById(demo).innerHTML = myStringArray[i];
//Do something
}
<div id="slider"></div>
<form>
<input id="input" type="text">
<input type=button onclick="addImg()" value="Add image url to slider"/>
</form>
如果我要将url添加到输入元素并提交它,则会将url添加到数组imgUrl中,但在列表#slides中它将不会被添加任何内容。
有人可以帮助我吗? 我会感激任何建议。
答案 0 :(得分:1)
我编辑了你的代码,这里正在运行演示:
var imgUrl = ['http://lorempixel.com/400/200/'];
function makeUL(array) {
// Create the list element:
list = document.createElement('ul');
list.id = "slides";
for(var i = 0; i < array.length; i++) {
// Create the list item:
var li = document.createElement('li');
li.className = "slide";
var img = document.createElement('img');
// Set its contents:
img.src = array[i];
li.appendChild(img);
//li.appendChild(document.createTextNode(array[i]));
// Add it to the list:
list.appendChild(li);
}
// Finally, return the constructed list:
return list;
}
// Add the contents of imgUrl to #slides:
document.getElementById('slider').appendChild(makeUL(imgUrl));
function addImg(){
var input = document.getElementById("input");
if (input.value != ""){
imgUrl.push(document.getElementById("input").value);
document.getElementById("slider").innerHTML = ''; //najprv sa to musi vycistit pretoze innerHTML to tam nepridavalo ako HTMl ale ako objekt, preto som to zamenil za appendChild
document.getElementById("slider").appendChild(makeUL(imgUrl));
}
}
<div id="slider"></div>
<form>
<input id="input" type="text">
<input type=button onclick="addImg()" value="Add image url to slider"/>
</form>
希望它有所帮助。