2011-12-16 75 views
1

我想解決以下問題:給定網頁上的鏈接,我想用指定的div元素的內容替換另一個元素的div元素的內容頁。說,只需將Google學術搜索頁面中的文字「站在巨人的肩膀上」加載到我現有的div元素中即可。JavaScript:用另一個HTML的內容替換元素

到目前爲止,如果實施下面的例子:

<html> 
<head> 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> 
</head> 
<body> 

<a href="http://www.whatsmyip.org/">Click me</a> 

<div id="myid">Text to be replaced</div> 

<script type="text/javascript"> 
    $("a").click(function() { 
     $.get(this.href, function(data) { 
     $("#myid").replaceWith($(data).find("#fb-root")); 
     }); 
     previous_page = location.href; 
     window.history.pushState({page: $(this).index()}, $(this).html(), $(this).attr('href')); 
     return false; 
    }); 

    window.onpopstate = function(event) { 
     location.reload(); 
    } 
</script> 

</body> 
</html> 

我包括爲了改變在地址欄中的URL,並允許用戶恢復網絡的先前狀態window.history沒有新內容的頁面。

現在,我有兩個問題:

  • 更換<code>div</code>元素似乎沒有工作,因爲從WhatIsMyIP整個頁面加載。
  • 使用Chrome時,整個頁面會從頭開始重複加載。我認爲,事件window.onpopstate被連續觸發。

感謝您的幫助!

+0

也許你的pushState問題可以通過使用該答案中提到的插件來解決:http:// stackoverflow。com/questions/5210034/history-pushstate – 2011-12-16 11:08:35

回答

2

相反,你可以結合一個click和超鏈接一個$.load

$('a').click(function(e){ 
    $('#myid').load($(this).attr('href')); 
    e.preventDefault(); //needed to prevent navigation! 
}); 

如果您需要頁面內的特殊元素,您可以附加任何選擇器。示例:

$('#myid').load($(this).attr('href') + ' div'); 

這將附加所請求頁面的所有div。

2

關於你提到的第一個問題

試試這個

$('#myid').load(this.href + ' #fb-root'); 

$.get(this.href, function(data) { 
    $("#myid").replaceWith($(data).find("#fb-root")); 
}); 
1

嘗試之前return false;

0

與內容添加event.preventDefault()如果我理解正確的話,你只是想更換指定的div元素的第一頁上的內容(與ID「身份識別碼」這種情況下的div元素)第2頁的div元素(第2頁是http://www.whatsmyip.org/

希望這可以幫助:

<html> 
<head> 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> 
</head> 
<body> 

<a href="http://www.whatsmyip.org/">Click me</a> 

<div id="myid">Text to be replaced</div> 

<script type="text/javascript"> 
$("a").click(function() { 
    $.get(this.href, function(data) { 
    var target_element_id_page2 = "element_id_page2"; 
    var target_element_type_page2 = "div"; 
    var respond= $('<div>' + data + '</div>');//You forgot this... It won't work unless you use it... 
    var target_element = respond.find(target_element_type_page2 + '#'+ target_element_id_page2)[0]; //There "might" be more div elements with the same id: that's why you specify index 
    var container = document.getElementById("myid"); 
    container.innerHTML = target_element.innerText; 
    }, "html"); 
</script> 

</body> 
</html> 

我拿出window.history.pushState和window.onpopstate,以便更好地回答你的問題沒有這兩個代碼有可能給任何錯誤。如果你把它們放回去,它應該完美地工作。雖然我不明白你爲什麼使用「previous_page = location.href;」。 previous_page沒有被聲明,你以後沒有使用它。糾正我,如果我錯了...