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

tec*_*ker 2 ajax jquery delegation

我想使用jQuery的.delegate()方法,因为我读过它比.live()执行得更好.

但是,当我使用.delegate()时,它不会将事件绑定到加载了ajax的内容.

任何人都可以帮我.delegate()工作吗?或者我是否坚持使用较慢的.live()来加载ajax内容?

   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!');
        });
     }, 

  };
Run Code Online (Sandbox Code Playgroud)

Tom*_*yBs 7

由于我没有获得许可,因此无法发表评论.但是使用delegate,您需要将事件绑定到通过AJAX刷新的内容之上.因此,如果您只是重新加载页面的一部分,请不要在该页面的内容上设置委托

<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>
Run Code Online (Sandbox Code Playgroud)

我认为在上面的情况下,这应该起作用,因为委托绑定在#parent上,而#parent没有被更新.显然这都是伪代码,但是你重新加载你委托的项目了吗?如果是这样,我认为你需要重新调整事件.我很确定'live'事件被绑定到文档,然后它只是比较目标以确保它与选择器匹配.委托从您指定的选择器开始,因此事件不需要冒泡到目前为止.(据我所知)