jQuery的 - 运行功能时,DOM变化功能、jQuery、DOM

2023-09-10 16:46:25 作者:╔爺們賊ゞ帅

我一直使用的liveQuery 到目前为止它的工作原理,但它使网页浏览似乎真的很慢。 所以我想找到这样的替代解决方案。

I've been using livequery so far which works, but it makes the page browsing seem really slow. So I'm trying to find a alternative solution for this.

我在安装,运行中的元素一些Ajax与某一类功能,如:

I'm attaching a function that runs some ajax on elements with a certain class, like:

$(".blah").each(function(){
  $.ajax({
      ...
      success: function(data) { 
        $(this).removeClass(".blah");
        // do other stuff
      }
  });
});

现在我已经迷上了不同元素的几个事件可以在DOM追加HTML,如:

Now I have several events hooked on different elements that can append html in the DOM, like:

$(".button").click(function(){
  $.ajax({
      ...
      success: function(data) { 
        $(this).append(data);
        // here, new elements with ".blah" class could be inserted in the DOM
        // the event above won't be fired...
      }
  });
});

我怎么能对上面运行,以便在第一AJAX功能,当DOM中的其他事件被更新?

How could I make so the first ajax function above runs when the DOM gets updated in the other events?

更新:

我还发现这个插件: http://www.thunderguy.com/semicolon/2007/ 8月14日/ elementready-的jQuery插件/

I also found this plugin: http://www.thunderguy.com/semicolon/2007/08/14/elementready-jquery-plugin/

你是否认为这将是一个更好的解决办法?从咋一看似乎,因为它允许您设置一个轮​​询区间,如果你将它设置为1秒或服用点这可能会降低CPU占用率。现在我测试吧:)

Do you think it would be a better solution? From a quick look it seems to, because it allows you to set a "polling" interval, which might decrease cpu usage if you set it to 1 sec or somehting. I'm testing it now :)

更新2:

不幸的是它仅适用于元素ID为一些奇怪的原因:(

Unfortunately it only works with element IDs for some weird reason :(

推荐答案

这是真实的,因为新的元素没有必然回调的事件,也只是新的新鲜元素。我会建议将事件绑定在他们创建(即内部的AJAX成功函数)刚刚结束,新创建的元素:

It's true because the new elements do not have events bound to callbacks, they are just new fresh elements. I would recommend to bind events on the newly created elements just after they are created (i.e. inside the ajax success function):

    $(".blah").each(function(){
      $.ajax({
          ...
          success: function(data) { 
            $(this).removeClass(".blah");
            // add handlers to new elements with class "button"
            $(this).find('.button').click(function() {  
                     $.ajax({
                          success: function(data) { 
                            $(this).append(data);
                          });
          }
      });
    }