(How to avoid?) jquery load method cause multiple event trigger in sub page
I use jquery load method to load sub page from another file to act as a template system, the code simplifies as following:
simple.html
- <ul>
<li><a href="#" onclick="loadMessage('Welcome Home')">HOME</a></li>
<li><a href="#page1" onclick="loadRoute('page1.html')">Page1</a></li>
</ul>
<div id="app">
</div>
- <script>
function loadRoute(url) {
$("#app").load(url);
}
function loadMessage(message) {
$("#app").text(message);
}
</script>
page1.html
- <div class="tag">
<h1>Page1</h1>
<script>
$(function(){
console.log("page1 loaded!");
$("#app").on("remove", ".tag", function(){
console.log("page1 removed!");
});
$( "#app" ).on( "click", "h1", function() {
console.log( $( this ).text() );
});
});
</script>
</div>
the template part works fine. But there are two problems in the above code:
first, after navigate between "HOME" and "Page1" links multiple times, the page1.html "h1" element will trigger multiple click events on single click.
second,
- $("#app").on("remove", ".tag", ...)
doesn't fire when navigate from Page1 to HOME, how can i accomplish this if i want to do something when my sub page is removed/replaced?
The attached zip file contains full source code of this simple test case. It must run on a local server if you are willing to check it out.
Thanks in advance.