您好,我一直在研究 Javascript 8 滑块拼图(包括事件侦听器在内),并且有代码生成移动数组(用户将点击哪个方块/div id)来解决拼图。
我的目标是让用户能够单击求解按钮,触发一个函数,该函数将播放谜题中的解决方案移动数组。
出于某种原因,我真正难过的地方是,在下面的代码中,点击不适用于循环的每次迭代——这一切都搞砸了。如果有人可以提供任何帮助或建议,我将不胜感激。
while(k < moves.length)
{
var move = "vp" + moves[k];
var el = document.getElementById(move);
el.click(); // simulate a users click on div
populate(); // update array
k++;
}
编辑 - 对于那些在下面询问的人是事件函数和更多代码......
function addEvent(elem, event, fn) {
// avoid memory overhead of new anonymous functions for every event handler that's installed
// by using local functions
function listenHandler(e) {
var ret = fn.apply(this, arguments);
if (ret === false) {
e.stopPropagation();
e.preventDefault();
}
return(ret);
}
function attachHandler() {
// set the this pointer same as addEventListener when fn is called
// and make sure the event is passed to the fn also so that works the same too
var ret = fn.call(elem, window.event);
if (ret === false) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
return(ret);
}
if (elem.addEventListener) {
elem.addEventListener(event, listenHandler, false);
} else {
elem.attachEvent("on" + event, attachHandler);
}
}
window.onload = function() {
var height = (newImg.height*0.33);
var width = (newImg.width*0.33333);
addEvent(document.getElementById('shuffle'),'click',initGame);
addEvent(document.getElementById('vp1'),'click',move);
addEvent(document.getElementById('vp2'),'click',move);
addEvent(document.getElementById('vp3'),'click',move); // ...
这是 el.click(); 函数的第一部分。打电话...
function move() {
var e = this;
var id = e.id.charAt(2);
var temp = 0;
//var images = e.getElementsByTagName('img');
//alert(images[0].className);
if (id == 1) {
if (document.getElementById("vp2").innerHTML.indexOf("selected") != -1)
{ temp = e.innerHTML;
e.innerHTML = document.getElementById("vp2").innerHTML;
document.getElementById("vp2").innerHTML = temp;
numMoves++;
}else if (document.getElementById("vp4").innerHTML.indexOf("selected") != -1)
{ temp = e.innerHTML;
e.innerHTML = document.getElementById("vp4").innerHTML;
document.getElementById("vp4").innerHTML = temp;
numMoves++;
}
}