我想解决以下问题:给定网页上的链接,我想将指定div
元素的内容替换div
为另一个页面的元素的内容。比如说,只需将 Google Scholar 页面中的文本“站在巨人的肩膀上”加载到我现有的div
元素中。
最新,如果实施以下示例:
<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>
我加入window.history
是为了更改地址栏中的 URL,并允许用户在没有新内容的情况下恢复网页的先前状态。
现在,我有两个问题:
- 元素的替换
<code>div</code>
似乎不起作用,因为加载了 WhatIsMyIP 的整个页面。 - 使用 Chrome 时,整个页面会从头开始一次又一次地重新加载。我认为,事件
window.onpopstate
是连续触发的。
感谢您的帮助!