我环顾了一段时间(可能花了一个小时搜索),但我找不到明确的答案。据我所知,我没有使用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