2010-08-06 54 views
0

我已經index.php文件是這樣的:AJAX:如何用同一個DIV中的鏈接替換DIV的內容?

<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的內容被調用,''workspace'DIV中成功鏈接'Two'。

但現在當我點擊鏈接「兩個」,然後'Hello World'不會出現在'工作區'DIV中,並且在沒有AJAX調用的情況下單獨打開。

如何強制此代碼使用上面的流使用鏈接「TWO」替換工作空間DIV的內容與'Hello World'?

感謝

回答

2

嘗試live()方法而不是click

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

live是當已分配事件存在或添加了內容/後加載使用。

+0

謝謝Sarfraz。它的工作。 – NAVEED 2010-08-06 17:59:35

+0

@NAVEED:不客氣:) – Sarfraz 2010-08-06 18:13:26

0

的問題是,使「阿賈克斯」鏈接,以便神奇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();   
}); 

或者,只是使用實時(如下所述)。

+0

我試過但沒有運氣。 – NAVEED 2010-08-06 17:43:38

+0

啊,你說得對。問題是查看「.ajax」的init方法僅在文檔加載時調用一次(所以後續更改不受影響)。將在一秒內更新... – 2010-08-06 17:49:54

相關問題