Loading content into div with Ajax … How do I target the same div with the new page loaded?

混江龙づ霸主 提交于 2019-12-22 01:21:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!