且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery的委托()不绑定的AJAX加载的内容事件

更新时间:2023-12-05 08:25:10

无法评论,但因为我没有权限。但是,随着委托,您需要绑定以上是通过AJAX刷新内容的事件。所以,如果你只是重新加载页面的一部分,不设置上的内容代表的是页

的一部分
 <脚本>
 $('#父)。代表(A,点击,函数(){
   // AJAX code替换#parent的内容,而不是父母本身
});
< / SCRIPT>
< D​​IV ID =父与GT;
      < D​​IV ID =AJAX>
          &所述; A HREF =#将实施例&所述; / a取代;
          < P>有的含量小于/ P>
      < / DIV>
< / DIV>
 

我觉得在上述情况下,这应该作为委托,势必在#parent和#parent没有被更新。显然,这是所有的伪code,但你重装您从委托​​的项目?如果是这样,我认为你需要重新绑定的事件。我是pretty的肯定'活'的事件被绑定到该文件,然后它只是比较对象,以确保它选择相匹配。代表将在您指定所以即使不需要泡了远选择。 (从我的理解)

I want to use jQuery's .delegate() method as I've read it performs much better than .live().

However, when I use .delegate() it doesn't bind events to the ajax loaded content.

Can anyone help me get .delegate() working? Or am I stuck using the slower .live() for ajax loaded content?

   var randomObject = {

     'config' : {
       'form' : '#someform',
       'select' : '#someselect',
       'container' : '#pagecontainer'
     },


     'init' : function() {  

        randomObject.formEffects();
        randomObject.ajaxFormSubmit();    
    },


     'formEffects' : function() {

        ////////////// DELEGATE WON'T WORK on AJAX loaded content!
        //$('randomObject.config.form).delegate('select', 'change', function() {
        $(randomObject.config.select).live('change', function() {
           $(this).closest('form').trigger('submit');
        });
     },


     'ajaxFormSubmit' : function($form) { 

        $(randomObject.config.container).load($form.attr('action')+' '+randomObject.config.container, $form.data('form_values'), function(response, status, xhr){
           alert('updated!');
        });
     }, 

  };

Can't comment yet as I don't have permission. But with delegate, you need to bind the event above the content that is refreshed via AJAX. So if you're only reloading part of a page, don't set the delegate on content that is part of that page

<script>
 $('#parent').delegate("a", "click", function(){
   // AJAX CODE replaces the contents of #parent but not parent itself
});
</script>
<div id="parent">
      <div id="ajax">
          <a href="#">example</a>
          <p>Some content</p>
      </div>
</div>

I think in the case above this should work as the delegate is bound on #parent and #parent is not being updated. Obviously this is all pseudo code, but are you reloading the item that you delegate from? If so I think you would need to rebind the events. I'm pretty sure 'live' events get bound to the document and it then just compares the target to make sure it matches the selector. Delegate starts at the selector you specify so the even doesn't need to bubble up as far. (from what I understand)