AJAX: How to replace content of a DIV with a link in same DIV?

不羁的心 提交于 2019-12-08 11:52:13

问题


I have index.php like this:

<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>

<a href='one.php' class='ajax'>One</a>

<div id="workspace">workspace</div>

one.php

<?php
$arr = array ( "workspace" => "<a href='two.php' class='ajax'>two</a>" );
echo json_encode($arr);
?>

two.php

<?php 
$arr = array( 'workspace' => "Hello World" );
echo json_encode($arr);
?>

ajax.js

jQuery(document).ready(function(){
    jQuery('.ajax').click(function(event) {
        event.preventDefault();
        // load the href attribute of the link that was clicked
        jQuery.getJSON(this.href, function(snippets) {
            for(var id in snippets) {
                // updated to deal with any type of HTML
                jQuery('#' + id).html(snippets[id]);
            }
        });
    });
});

When index.php is loaded, there is a link(One) and a DIV(workspace). When I click 'One' link then content of one.php is called and link 'Two' appeared in 'workspace' DIV successfully.

But now when I click link 'Two' then 'Hello World' does not appear in 'workspace' DIV and opened separately without AJAX call.

How to force this code to replace content of workspace DIV with 'Hello World' using link 'TWO' with above flow?

Thanks


回答1:


Try the live() method instead of click:

jQuery('.ajax').live('click', function(event) {
  // your code
});

The live is used when the content you have assigned events to is either present or is added/loaded later.




回答2:


The problem is that the init method that makes the ".ajax" links so magical is only being called once, when the document loads. When you replace the html the magic is lost.

Try this:

function assignLinks() {

    jQuery('.ajax').click(function(event) {
            event.preventDefault();
            // load the href attribute of the link that was clicked
            jQuery.getJSON(this.href, function(snippets) {
                for(var id in snippets) {

                    // updated to deal with any type of HTML
                    jQuery('#' + id).html(snippets[id]).click( function() {
                        assignLinks();
                    });
                }
            });
        });

}

jQuery(document).ready(function() {
    assignLinks();        
});

Or, just use live (as stated below).



来源:https://stackoverflow.com/questions/3426276/ajax-how-to-replace-content-of-a-div-with-a-link-in-same-div

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