Why does jQuery lose an โ€œeventโ€ (click) when loading some content?

I am trying to load content using the following script when I select pages in the sidebar. This script works without problems:

if(Modernizr.history) { var newHash = "", $wrapperTag = $("#main-content"), contentTag = '#main-content-inside', activeClass = 'active'; $("#sidebar").delegate("a", "click", function() { _link = $(this).attr("href"); history.pushState(null, null, _link); loadContent(_link); return false; }); function loadContent(href){ $wrapperTag .find(contentTag) $wrapperTag.load(href + " "+contentTag+" ", function(response, status, xhr) { $("#sidebar a").removeClass(activeClass); $('#sidebar a[href$="'+href+'"]').addClass(activeClass); $("#menu").bind('click',function(){ $(this).showSidebar(); }); }); } 

This script works without problems, and my HTML template looks something like this:

HTML template

 <div id="sidebar"> <nav> <ul class="ul-vert"> <li><a href="page1.html">Page 1</a></li> <li><a href="page2.html">Page 2</a></li> ... <li><a href="pageN.html">Page N</a></li> </ul> </nav> </div> <div id="main-content"> <div id="main-content-inside"> <p id="menu">Show / Hide Sidebar</p> <div class="text desc">(Content)</div> </div> </div> 

I have a p # menu tag as an option to show or hide the sidebar. This only works until I load any page , after which I lose the click event.

So basically my question is:

Why does jQuery play an event after changing content? I could solve this by adding the p # menu to loadContent again , but I want to understand how jQuery works.

Thanks!

+4
source share
1 answer
 $('.fatherDiv').on('click','.childDiv', {} ,function(e){ //insert your code here }) 

This will associate event handlers with elements of the DOM selector not only now, but also in the future (selectors are added to the DOM after bindings). The click event now fires, even certain selectors are added or replaced with new DOM elements.


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

+10
source

Source: https://habr.com/ru/post/1485919/


All Articles