我環顧了一段時間(可能花了一個小時搜索),但我找不到明確的答案。據我所知,我沒有使用jQuery或AJAX,只使用普通的JavaScript。下面是它的樣子:JavaScript - 非常簡單的代碼,但功能尚未定義
var i;
var displayimg = document.getElementsById("displayimg"); // I'm not sure what I'm doing here. I thought that the onclick event might be in the wrong scope, so I tried setting it from JavaScript instead. It didn't work.
var imgb = document.getElementsByClassName("imgb");
for (i = 0; i < imgb.length; i += 1) {
imgb[i].addEventListener("click", setSlide(i));
console.log("successful");
}
var maxIndex;
var minIndex;
function startSlide(max, min) { // this function comes from the html body onload.
"use strict";
maxIndex = max;
minIndex = min;
showSlide(1);
}
function setSlide(n) { // this function comes from the .imgb buttons.
"use strict";
showSlide(n);
console.log("OK");
}
function showSlide(n) {
"use strict";
if (n > maxIndex) {
n = minIndex;
} // if number exceeds 3, go back to 1 (top)
if (n < minIndex) {
n = maxIndex;
} // if number deceeds 1, go back to 3 (bottom)
for (i = 0; i < imgb.length; i += 1) { // loops through all imgb
imgb[i].className = imgb[i].className.replace(" active", ""); // removes active class from all imgb
}
document.getElementsById("displayimg").style["background-image"] = "url('pre".concat(i, ".png')");
imgb[n - 1].className += " active";
console.log("slide updated");
}
<div id="displayimg" style="background-image:url('pre1.png');"></div>
<div style="text-align:center;">
<span class="imgb"></span>
<span class="imgb"></span>
<span class="imgb"></span>
</div>
我可能會搞砸了劇本,我看了很多教程和答案的SO和那種只是搗碎他們在一起,希望它會工作。當我嘗試通過JSLint運行它時,以及每個「for」循環都出乎意料,似乎反覆出現的問題就是「超出範圍」。 這個問題已經打破了我。每當我嘗試新的解決方案時,我都覺得自己陷入了一系列未解決的問題中。請,任何幫助表示讚賞。
這是'document.getElementById'不'document.getElementsById'。 – Nisarg
並且'(「click」,setSlide(i));'< - 錯誤,因爲您調用它不分配它。 – epascarello
「*只是把它們混合在一起,希望它能起作用*」,現在你想讓我們修復它?你真的嘗試過什麼?你的調試器說什麼?您尚未列出您嘗試解決此問題的所有步驟。 – zero298