在一个论坛上,我实现了一个“ spoiler tag”,除了一点点之外,它都能正常工作。当人们使用快速回复或使用AJAX和JS编辑帖子来动态添加帖子时,该功能不会拾取新添加/编辑的剧透标签。我在这里尝试了几种方法来解决此问题,但到目前为止,似乎还没有一种方法可行。我不能正确使用on()功能吗?

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;
        }

    });

最佳答案

这是行不通的,因为只能将事件添加到DOM中实际存在的元素中。如果元素是动态添加的,则您必须从静态父元素(例如,像这样:

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


静态父元素会将事件委派给所有类为spoilertagbutton的子级,即使稍后添加。

因为应该避免在Stackoverflow上复制/粘贴(甚至从自己的答案中复制/粘贴)-我已经用类似的问题here回答了这个问题,并提供了更多有关事件委托的信息和jquery参考。

关于javascript - 改变时不采用新的dom元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26317225/

10-12 12:45
查看更多