jQuery on: losing attached event after rendering partially by AJAX call

来源:互联网 发布:ubuntu samba 权限 编辑:程序博客网 时间:2024/05/20 22:27

In the menu bar, there is a saved searches link with a number meaning the total number of saved searches.



In one of the page, there is save search button allowing you to save one search, after saved, the number above should be updated by partially rendering the link .

 the following code before update:

 this.element.find('.savedSearchButton-Menu').on('click', function () {}

Initially, I thought $.on is the same as $.live method, attach the event handler for the selector for ever (now and future), which means event handler is still valid after adding or replacing the DOM elements.. But $.on bind the event handlers only for the selector exists at the time of binding.


if I want to make $.on to work as the same as $.live, I need do the following changes:

 $(document.body).on('click','.savedSearchButton-Menu', function(){                if (window.isUserLoggedIn==="true") {                    window.location.href='/myatc/searches.xhtml';                }                else{                    $('[id$=myatcLoginLink]').trigger('click');                    atc.publish('savedSearchIntent','/myatc/searches.xhtml');                }            });



This will bind the event handlers to the DOM selector elements not only now, but also in future. Now the click event fires even the specific selectors are replaced with new DOM elements.


Reference: http://blog.revathskumar.com/2013/10/jquery-on-avoid-losing-event-binding-for-ajaxed-contents.html

0 0
原创粉丝点击