2008-11-06 135 views
54

是否有一種簡單的方法來修改此代碼,以便在同一個窗口中打開目標URL?Javascript:在同一個窗口中打開新頁面

<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>`` 

回答

69

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鏈接的可以說是更好的方法的概述。

What's the best way to replace links with js functions?

7
<a href="javascript:;" onclick="window.location = 'http://example.com/submit.php?url=' + escape(document.location.href);'">Go</a>; 
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 ...爲什麼不把它添加到服務器端?

1

所以通過在href結尾添加URL,每個鏈接都會在同一個窗口中打開?你也可以在HTML中使用_BLANK來做同樣的事情。

3

試試這個它爲我工作在IE 7和IE 8

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

下面是我工作:

<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> 
相關問題