1

我想解决以下问题:给定网页上的链接,我想将指定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是连续触发的。

感谢您的帮助!

4

4 回答 4

2

关于你的第一个问题

试试这个

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

而不是这个

$.get(this.href, function(data) {
    $("#myid").replaceWith($(data).find("#fb-root"));
});
于 2011-12-16T11:03:59.317 回答
2

您可以在超链接上组合 aclick和 a $.load

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

如果您想要页面中的特殊元素,您可以附加任何选择器。例子:

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

这将附加请求页面的所有 div。

于 2011-12-16T11:04:36.530 回答
1

尝试添加event.preventDefault()之前return false;

于 2011-12-16T11:07:15.980 回答
0

如果我理解正确,您只想用 page2 中的 div 元素的内容(page2 为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 未声明,之后您不再使用它。如果我错了,请纠正我...

于 2015-03-30T06:15:38.237 回答