2014-10-11 62 views
0

在論壇上,我已經實現了一個「擾流標籤」它工作正常,除了一點點。當人們使用快速回復,或編輯帖子利用AJAX和JS動態添加帖子時,該功能不會拾取新添加/編輯的擾流標籤。我在這裏嘗試了一些方法來解決這個問題,但目前沒有任何方法可行。我沒有正確使用on()功能嗎?關於更改不拾起新的DOM元素

http://jsfiddle.net/WASasquatch/ho5ewoj2/

更新與它下面的幫助似乎捕捉到了新的元素,而是功能的第二次點擊後,不再向上滑動。

功能

$(document).on('click', '.spoilertagbutton', function() { 

     var spoilerButton = $(this), 
      parentSpoiler = $(this).parent().closest('.spoilertag'), 
      spoilerContent = parentSpoiler.find('.spoilercontent'), 
      spoilerHidden = true; 

     spoilerButton.css('backgroundColor', 'rgba(255,255,255,0.2)'); 
     spoilerButton.mouseleave(function(){ 
       spoilerButton.css('backgroundColor', 'rgba(0,0,0,0.4)'); 
     }); 

     if (spoilerHidden) { 
      spoilerButton.html('Hide Content'); 
      spoilerContent.slideDown(function() { 
       $(this).children().slideDown(); 
      }); 
      spoilerHidden = false; 
     } else { 
      spoilerButton.html('Show Content'); 
      spoilerContent.slideUp(function() { 
       $(this).children().slideUp(); 
      }); 
      spoilerHidden = true; 
     } 

    }); 

回答

2

這不起作用,因爲事件只能被添加到實際上是在DOM元素。如果動態添加元素,則必須從靜態父元素中委派事件,例如,像這樣:

$(document).on("click", ".spoilertagbutton", function() 
    { 
    // your function 
    } 
); 

靜態父元素將委託事件與類spoilertagbutton所有的孩子,即使後來添加的。

因爲它應該避免複製/粘貼到Stackoverflow(即使從自己的答案) - 我已經回答了類似的問題here與一些進一步的信息和事件委託jQuery的參考。

+0

似乎找到它們,但不再滑落。查看更新代碼。 – WAS 2014-10-11 17:48:48

+0

@ user3701746您是否擁有小提琴,因爲它更容易檢查實際的html/js是怎麼回事?只看代碼,我會認爲問題在於你設置了spoilerHidden = true;每次單擊spoilertagbutton時,它都不會滑動。所以你應該嘗試一下,如果它在點擊函數外面聲明spoilerHidden變量爲全局變量,它可以解決它。 – 2014-10-11 17:55:57

+0

添加了小提琴,對不起。 – WAS 2014-10-11 18:06:23