JavaScript:在同一个窗口中打开新页面

59
有没有一种简单的方法来修改这段代码,使目标URL在相同窗口中打开?

<a href="javascript:q=(document.location.href);void(open('http://example.com/submit.php?url='+escape(q),'','resizable,location,menubar,toolbar,scrollbars,status'));">click here</a>``

8个回答

83

“false” 应该表示您可以使用返回按钮返回到创建窗口的页面,对吗?但这在我的情况下无法正常工作。 - Noumenon

74
window.open()的第二个参数是一个字符串,表示目标窗口的名称。 将其设置为:"_self"。
<a href="javascript:q=(document.location.href);void(open('http://example.com/submit.php?url='+escape(q),'_self','resizable,location,menubar,toolbar,scrollbars,status'));">click here</a>


旁注:下面的问题概述了一种可能更好的将事件处理程序绑定到HTML链接的方法。

什么是用js函数替换链接的最佳方法?


7
<a href="javascript:;" onclick="window.location = 'http://example.com/submit.php?url=' + escape(document.location.href);'">Go</a>;

3
这是我尝试过的有效方法:
<button name="redirect" onClick="redirect()">button name</button>
<script type="text/javascript">
function redirect(){
var url = "http://www.google.com";
window.open(url, '_top');
}
</script>

3

尝试这个方法,它在IE 7和IE 8中可行。

 $(this).click(function (j) {
            var href = ($(this).attr('href'));
            window.location = href;
            return true;

1

那么通过在 href 的末尾添加 URL,每个链接都将在同一窗口中打开?您也可以在 HTML 中使用 _BLANK 来实现相同的效果。


1
如果我是你,我会稍微以不同的方式处理它。在页面加载时更改文本链接,而不是在单击时更改。我将用jQuery举例,但这也可以很容易地在原生JavaScript中完成(尽管jQuery更好)。
$(function() {
    $('a[href$="url="]')    // all links whose href ends in "url="
        .each(function(i, el) {
            this.href += escape(document.location.href);
        })
    ;
});

然后像这样编写您的HTML:

<a href="http://example.com/submit.php?url=">...</a>

这样做的好处是人们可以看到他们点击的内容(href已经设置),并且它可以从你的HTML中删除JavaScript。

话虽如此,看起来你正在使用PHP...为什么不在服务器端添加呢?


0

尝试

<a href="#" 
   onclick="location='http://example.com/submit.php?url='+escape(location)"
   >click here</a>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接