簡體   English   中英

將jquery remove方法設置為動畫完成時的回調不起作用

[英]Setting jquery remove method as callback on animation complete doesn't work

我正在做一個小游戲,在這個游戲中,我經常需要一場災難。 這場災難必須動搖我的MainFrame元素,並從建築物數組和DOM中刪除類.House的所有元素。

該代碼在一定程度上有效,問題在於它不會從DOM中刪除元素,而只是從數組中刪除元素。 你能幫我讓它工作嗎 我第一次使用此網站,所以希望我不要遺漏任何相關內容。

setInterval(function() {

    var iDisasterChance = getRandomNumber(1, 12);

    if (iDisasterChance === 1)
    {
        $(".MainFrame").effect("shake", {times: 8}, 4000);
        //$(".House").effect("explode", {pieces: 24}, 4000);
        $(".House").effect("explode", {pieces: 24}, 4000,  $(".House").remove); // TODO: bug - leaves elements in the dom
        //$(".House").remove();
        oCity.aBuildings.length = 0;
        console.log(iDisasterChance +' of 12');
        console.log('*** DISASTER ! AVOIDED ***');
        console.dir(oCity.aBuildings);
        return false;
    }
    else
    {
        console.log(iDisasterChance +' of 12');
        console.log('*** DISASTER AVOIDED ***');
    }
}, 10000);

嘗試這種方式。 您需要remove()而不是remove並在回調中,因為您丟失了remove方法中jquery對象的上下文。

$(".House").effect("explode", {pieces: 24}, 4000,  function(){
    $(this).remove(); //now this will get executed once your animation effect is complete and this represents the .House where the effect happened.
});

如果要remove所有.House,則必須remove

$(".House").effect("explode", 
                              {pieces: 24}, 4000, 
                              $(".House").remove.bind($(".House"))); //bind will set the context to that of .House.

要么

   $(".House").effect("explode", {pieces: 24}, 4000,function(){
          $(".House").remove();
   });

原因是您這樣做的時間:

$(".House").effect("explode", {pieces: 24}, 4000,  $(".House").remove));

OfCourse remove方法將在回調中設置為上下文,該上下文中最有可能是DOMelement而不是jquery object上下文(如在常規回調中看到的那樣,將this作為DOM元素獲取,並且它沒有jquery版本的remove方法)。 因此,您可以使用function.bind綁定上下文或$.proxy也可以僅在回調中進行操作。

我不知道此函數將在哪個確切的上下文中工作,但我注意到有關您的代碼的兩件事。

  1. 您當前具有的效果后代碼: $('.House').remove應該是$('.House').remove()並帶有方括號,否則您只是引用該方法而未實際調用它。

  2. 您的if語句僅在其兩種情況之一中返回,同樣,我不確定您打算做什么,但我相信您可能希望return true; else子句中。

希望這些建議對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM