5 回答

TA貢獻1765條經驗 獲得超5個贊
替換location.href
為window.open
,并使用'_blank'
如下:
window.open(sites[i],'_blank');

TA貢獻1817條經驗 獲得超14個贊
<h1 onclick="randomSite();">Click<br>Me</h1>
<script>
var sites = [
'http://www.google.com',
'http://www.youtube.com',
'http://www.facebook.com',
'http://www.stackoverflow.com'
];
function randomSite() {
var i = parseInt(Math.random() * sites.length);
window.open(sites[i], '_blank');
}
</script>

TA貢獻1802條經驗 獲得超5個贊
可以設置一個像這樣的簡單結構來執行這個
<body>
<p>Click the button to open a new tab </p>
<button onclick="NewTab()">
Open Google
</button>
<script>
function NewTab() {
window.open( "https://www.google.org", "_blank");
}
</script>
</body>
</html> ```

TA貢獻1757條經驗 獲得超8個贊
在您的randomSite()
功能交換location.href = sites[i];
中:
window.open('http://' + sites[i],'_blank');
也許您可以以某種方式使用 location.href 命令,我不熟悉它。但是打開一個窗口是直截了當的,如果您添加屬性“_blank”,它將在新選項卡中打開。

TA貢獻1828條經驗 獲得超6個贊
創建一個新的HTMLAnchorElement并使用它的click方法(不是click事件):
function onHeadingClicked( e ) {
const a = document.createElement( 'a' );
a.target = '_blank';
a.href = getRandomUrl();
a.click();
}
<h1 onclick="onHeadingClicked(event)">Click me</h1>
添加回答
舉報