问题
I'm loading a php page into a div using the following:
<li><a href="content1.php" data-target="#right_section">Some Content</a></li>
$('[data-target]').click( function (e) {
var target = $($(this).attr('data-target'));
target.load($(this).attr('href'));
e.preventDefault(); // prevent anchor from changing window.location
});
<div id="right_section"></div>
This works perfectly fine.... however:
I want to load another page into that same div, but the link is in content1.php . I basically want it to overwrite itself with another page when a link is clicked.
Thoughts ?
回答1:
You should use jQuery's .on event handler to bind the click event.
http://api.jquery.com/on/
In your case it would look like:
Main Page:
<li><a href="content1.php" class="load-external" data-target="#right_section">Some Content</a></li>
<div id="right_section"></div>
<script>
$(document).ready(function()){
$('body').on('click', 'a.load-external', function(e){
var target = $( $(this).attr('data-target') );
target.load( $(this).attr('href') );
e.preventDefault();
});
});
</script>
content1.php
<li><a href="content2.php" class="load-external" data-target="#right_section">Some Content 2</a></li>
What this would do is bind the click event on all a.someclass elements inside body and that includes dynamically created elements.
Btw, I added the .someclass so that it will not bind to all a elements but only to specific a elements that you want to load a content from.
来源:https://stackoverflow.com/questions/30429543/loading-content-into-div-with-ajax-how-do-i-target-the-same-div-with-the-new