AJAX:如何用同一个DIV中的链接替换DIV的内容?

时间:2010-08-06 17:38:37

标签: php ajax json html hyperlink

我有这样的index.php:

<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]);
            }
        });
    });
});

加载index.php时,会有一个链接(一个)和一个DIV(工作空间)。当我点击“One”链接时,会调用one.php的内容,并且“Two”链接成功出现在“工作区”DIV中。

但现在当我单击链接'Two'时,'Hello World'不会出现在'workspace'DIV中,并且在没有AJAX调用的情况下单独打开。

如何使用上面的流程链接'TWO'强制此代码将工作空间DIV的内容替换为'Hello World'?

由于

2 个答案:

答案 0 :(得分:2)

尝试使用live()方法代替click

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

当您分配了事件的内容存在或稍后添加/加载时,将使用live

答案 1 :(得分:0)

问题是,当文档加载时,使“.ajax”链接如此神奇的init方法只被调用一次。当你替换html时,魔法就会丢失。

试试这个:

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();        
});

或者,只需使用live(如下所述)。