gpt4 book ai didi

javascript - 执行 elem.click();在 javascript 循环中并不总是有效 - 计时?

转载 作者:行者123 更新时间:2023-11-30 06:40:05 25 4
gpt4 key购买 nike

你好,我一直在研究一个 Javascript 8 slider 拼图(包括事件监听器在内),并且有代码生成一组移动(用户会点击哪些方 block /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++;
}
}

最佳答案

jQuery:

$(el).click();

Javascript:

var etype = 'click';
if (el.fireEvent) {
(el.fireEvent('on' + etype));
}else{
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}

关于javascript - 执行 elem.click();在 javascript 循环中并不总是有效 - 计时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12054556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com