开发者

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

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="wor开发者_如何学Gokspace">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


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜