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

故事扮演 提交于 2019-12-04 21:49:40

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.

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