0

我在这里有一个点击处理程序的链接。href 充满了我需要的信息。但我不希望点击打开此链接。所以我做了 event.preventDefault ,它工作正常。但我需要 target="_top" ich 有人点击链接。这甚至可能吗?

4

2 回答 2

0

event.preventDefault();函数更改为return false;并使用 scrollTop 进行 html 动画:$('html, body').animate({scrollTop:0});

现在链接没有跟随 href 但它滚动到顶部

于 2011-12-06T13:00:29.413 回答
0

如果您阻止链接的默认操作,我认为您正在做其他事情。如果其他事情涉及更改窗口位置,并且您想更改顶部窗口的位置,则可以使用window.top它来引用它,然后通过location属性设置其位置,例如:

window.top.location = /* ... */;

例如(现场示例):

HTML:

<a id="theLink" href="http://jsbin.com">This link</a>
says jsbin.com and doesn't have <code>target="_top"</code>,
but will actually go to stackoverflow.com and do it
in the top window. (Seems a bit evil.)

JavaScript:

jQuery(function($) {

  $("#theLink").click(function(event) {
      window.top.location = "http://stackoverflow.com";
      return false;
  });

});

...但这提出了为什么不让链接完成其工作的问题。:-)

或者,如果您尝试添加target="_top"到单击时没有链接的链接,您可以执行以下操作:

var link = /* ...get the link element, e.g., $("#theLink") or whatever */;
$("#theLink").click(function() {
    link.attr("target", "_top");
});

请注意,我并没有阻止那里的默认操作。

不过,我不想保证这一定会起作用——最好在他们点击链接之前设置属性。

于 2011-12-06T11:07:37.493 回答