Queue() / dequeue() JQuery工作不正常

Queue() / dequeue() JQuery not working properly

本文关键字:工作 不正常 JQuery Queue dequeue      更新时间:2023-09-26

我一直在使用CoffeScript和JQuery。我需要创建一个简单的动画。

我试着使用delay,但我根本不理解它,所以我之前读了一个问题:

本页链接

所以我决定使用队列;主要的问题是,虽然队列中有更多的元素,但只考虑动画的最后一个元素。

我希望你能帮助我:),你可以找到下面的代码。

队列中的所有元素(CoffeScript)。

    for proc in listaDeProcesos
    id = proc.id
    nombre = proc.nombre
    idFinal = "#{id}#{nombre}"
    tiempo = parseInt(proc.tejecucion)
    $("#animacion").queue('chain',(next)->
            $("##{idFinal}").fadeOut(tiempo,->
                    next()
                )
        )

dequeue函数调用:

        $("#animacion").dequeue('chain')

恭喜!对所有JavaScript(或CoffeeScript)开发人员来说,这是一个必经之路。你最终一定会遇到的。原因有两方面:

  • JavaScript(和CoffeeScript)变量是函数作用域,而不是块作用域
  • 关闭

基本上,每次迭代创建一个函数,其中引用变量 idFinal,而不是在该循环迭代中引用idFinal。所以当以后的迭代改变idFinal时,它会改变你所创建的所有函数。这里有一个更简单的行为示例:

JavaScript闭包内循环-简单的实际例子

在CoffeeScript中解决这个问题的一种方法是使用do构造引入一个新的作用域:
for {id, nombre, tejecucion} in listaDeProcesos
  do (idFinal = "#{id}#{nombre}", tiempo = parseInt(tejecucion)) ->
    $("#animacion").queue 'chain', (next) ->
      $("##{idFinal}").fadeOut tiempo, next

我找到了另一种解决方案,以防别人有同样的问题,我写下面的代码,谢谢:)

所有的代码都在coffeescript中

动画元素类

class animatedElement
constructor: (@element,@time) ->
showInfo: ->
    alert ("#{@element} >> #{@time}")

你想要动画的迭代:

for proc in listaDeProcesos
    id = proc.id
    nombre = proc.nombre
    idFinal = "#{id}#{nombre}"
    tiempo = parseInt(proc.tejecucion)
    elemento = new animatedElement($("##{idFinal}"),tiempo)
    queue.push(elemento)

配套功能
showAnimation = ()->
if (queue.length > 0)
    tiempo = queue[0].time
    (queue.shift().element).fadeOut(tiempo, showAnimation)

最后你只需要调用

showAnimation()

我希望它能对别人有用。