Reputation: 55
I have this code in the file assets/URL.js
:
$(function(){
$("a").on("click", function () {
event.preventDefault();
var TheURL = $(this).attr('href');
if(TheURL){
$("#MyDiv").load(TheURL , { name: '' },
function() {
alert("done");
});
}
});
});
And what it does is that if an <a>
element is clicked, the function above prevents the page from going to that page then it gets the url and load it into the div
with the id MyDiv
.
Now this is the code of index.html
:
<html>
<head>
<script type="text/javascript" src="assets/URL.js?v=1"></script>
</head>
<body>
<div id="MyDiv">
<a href="files/1.html"></a>
</div>
</body>
</html>
and the code of files/1.html
is:
<a href="2.html">2</a>
now, when I click on <a>
in the file index.html
the content of the <div>
with the id MyDiv
changes the the content of file/1.html
without the page reloading.
But when I click <a>
in the file file/1.html
the page reloads and goes to file/2.html
and doesn't follow the code in assets/URL.js
, how can I force it to follow it and just replace the content of the <div>
with the id MyDiv
?
Upvotes: 0
Views: 28
Reputation: 1280
You need to setup the eventhandlers again when the dynamic html is loaded, right now you only bind the click event to the existing A tags in index.html, not the future ones in dynamic loaded content like 1.html
You could try something like:
$(function(){
RefreshEventHandlers();
});
function RefreshEventHandlers() {
$("a").on("click", function () {
event.preventDefault();
var TheURL = $(this).attr('href');
if(TheURL){
$("#MyDiv").load(TheURL , { name: '' },
function() {
alert("done");
RefreshEventHandlers(); // bind click to newly added A tags.
});
}
});
}
To make sure the click event handlers are set on all new A tags
Upvotes: 2