Reputation: 18876
I am calling ajax via jquery in an effort to load an href. The html seems to load correctly. However, the html that is loaded (href) does not actually work. Specifically, I can't figure out why once the link loads via ajax, it doesn't actually do anything when I click it. No errors in firebug, just dead link. Is my .on() method incorrect?
home.html
<html>
<head></head>
<body>
<div id="connections">Placeholder Text</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var uri='home-ajax.html'; //first find out if this is created yet
var myVar=setInterval(function(){example_ajax_request()},8000); //to do that check for it ev. 8 sec.
function example_ajax_request() {
$.ajax({
type: 'GET',
url: 'home-ajax.html', //checking
dataType: 'html', //html is content inside home-ajax.html
success: function() {
$('#connections').load('home-ajax.html'); //if home-ajax exists replace connections div with its content
clearInterval(myVar); //stop the 8 sec. timer
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
$('myLink').on('click', function(e) { //using .on to actively bind new href link from ajax()
document.location.href="http://www.cnn.com";//when href with id='myLink' is clicked, go to www.cnn.com
});
</script>
</body>
</html>
home-ajax.html
<p><a href="#" id="myLink">CNN</a></p>
Upvotes: 0
Views: 538
Reputation: 50767
That element did not exist on page load, so you can't bind a click function directly to it. You have to delegate the click to a static element.
$(document).on('click', '#myLink', function(e){
e.preventDefault(); // stop default action
document.location.href="http://www.cnn.com"; //do work
});
Upvotes: 1