这条线
'<button onClick="morPrev();"> < </button>
mordorscreens[i] <button onClick="morNext();"> > </button> ';
应该看起来像
'<button onClick="morPrev();"> < </button>'
+ mordorscreens[i] + '<button onClick="morNext();"> > </button>';
我认为公开变量 i 以迭代图像是一个坏主意。最好用 Javascript 而不是 HTML 分配事件处理程序。
试试这个代码
HTML
<div id="ss1">
<button id="previous"> < </button>
<span id="imageSpan"></span>
<button id="next"> > </button>
</div>
Javascript
var mordorscreens = [];
mordorscreens[0] = '<img src="http://i.imgur.com/83HCt.png" alt="scrns1">';
mordorscreens[1] = '<img src="http://i.imgur.com/5mWIy.png" alt="scrns1">';
mordorscreens[2] = '<img src="http://i.imgur.com/pPafl.png" alt="scrns1">';
function morshots() {
var i = 0;
var elem = document.getElementById('imageSpan');
elem.innerHTML = mordorscreens[i];
// Data Attribute that holds the initial
// image number
elem.setAttribute('data-number', i);
}
// Call The function
morshots();
// Assign Event handlers
var buttons = document.getElementsByTagName('button');
for (var j = 0; j < buttons.length; j++) {
// Add Click events to the button
buttons[j].addEventListener('click', clickHandler);
}
function clickHandler() {
var elem = document.getElementById('imageSpan');
// Store the current Image Number in a HTML5 data-attribute
var currImage = parseInt(elem.getAttribute('data-number'), 10);
if (this.id === 'previous') {
currImage--;
currImage = currImage < 0 ? 2 : currImage;
}
else if (this.id === 'next') {
currImage++;
currImage = currImage > 2 ? 0 : currImage;
}
// Set the current Image Number
elem.setAttribute('data-number', currImage);
elem.innerHTML = mordorscreens[currImage];
}
检查 JSBin 演示