2017-04-30 147 views
-1

我有一個幻燈片放在一起,但我無法使用onClick插入一個額外的圖像。我錯過了什麼?將圖像添加到javascript幻燈片

function newDivs(n) { 
 
    var i; 
 
    var x = document.getElementsById("photo"); 
 
    if (n > x.length) { 
 
    slideIndex = 1 
 
    } 
 
    if (n < 1) { 
 
    slideIndex = x.length 
 
    }; 
 
    for (i = 0; i < x.length; i++) { 
 
    x[i].style.display = "none"; 
 
    } 
 
    x[slideIndex - 1].style.display = "block"; 
 
}
<input type="text" name="photo" id="photo" value="http://static.boredpanda.com/blog/wp-content/uuuploads/cute-baby-animals/cute-baby-animals-23.jpg" /> 
 
<button id="addPicture" onclick="newDivs(+1)">Add New Image</button>

+0

你得到一個錯誤信息?它說什麼? – WillardSolutions

+0

onclick沒有插入任何圖像,也沒有'getElementsById'這樣的東西。 – xandercoded

+0

您能解釋一下您得到的錯誤是什麼以及您期望或期望的行爲是什麼? –

回答

0

你有很多失誤開始:

錯誤:

變種X = document.getElementsById( 「照片」);

右:

變種X =的document.getElementById( 「照片」)VAL。

0

你需要了解一些事情。

  • 當您想對多個元素執行操作時,請不要嘗試id。 (ID總是返回只有一個元素,它不能與多個元素運行

  • 你的JavaScript功能失常getElementsById正確的是getElementById只是因爲正如我所說的ID返回單個元素(getElementById - 。只是刪除( S)從功能。

  • 嘗試使用查詢選擇,就像我在你的例子都習慣了。(querySelectorAll

  • 查詢選擇功能將幫助你很多!如果你是在JavaScript中新如果你可以試試jQuery這對你來說真的很容易

  • 如果你想顯示圖像,你需要使用img標籤。現在你從輸入標籤獲取URL並試圖隱藏它們是沒有意義的;

  • 這裏是您的解決方案

var i= 0; 
 
var slideIndex = 0; 
 
function newDivs(n) { 
 
    var i; 
 
    var x = document.querySelectorAll(".photo"); 
 
    console.log(x); 
 
    if (n > x.length) { 
 
    slideIndex = 1 
 
    } 
 
    if (n < 1) { 
 
    slideIndex = x.length 
 
    }; 
 
    
 
    for (var index = 0; index < x.length; index++) { 
 
    console.log(x[index].style); 
 
    x[index].style.display = 'none'; 
 
    } 
 
    console.log(slideIndex); 
 
    x[slideIndex].style.display = "block"; 
 
}
<input type="text" class="photo" name="photo" id="photo" value="http://static.boredpanda.com/blog/wp-content/uuuploads/cute-baby-animals/cute-baby-animals-23.jpg" /> 
 
<button id="addPicture" onclick="newDivs(+1)">Add New Image</button>

相關問題