如何让这个 Javascript 函数在新标签页中打开网站?

如何使此功能在新选项卡中打开链接?我在某处读到我应该使用锚元素而不是使用 JS 打开链接。


<h1 onclick="randomSite();">Click<br>Me</h1>

            <script>

    var sites = [

        'www.google.com',

        'www.youtube.com',

        'www.facebook.com',

        'www.stackoverflow.com'

    ];


    function randomSite() {

        var i = parseInt(Math.random() * sites.length);

        location.href = sites[i];

    }

</script>


撒科打诨
浏览 97回答 5
5回答

POPMUISE

替换location.href为window.open,并使用'_blank'如下:window.open(sites[i],'_blank');

大话西游666

<h1 onclick="randomSite();">Click<br>Me</h1>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <script>&nbsp; &nbsp; var sites = [&nbsp; &nbsp; &nbsp; &nbsp; 'http://www.google.com',&nbsp; &nbsp; &nbsp; &nbsp; 'http://www.youtube.com',&nbsp; &nbsp; &nbsp; &nbsp; 'http://www.facebook.com',&nbsp; &nbsp; &nbsp; &nbsp; 'http://www.stackoverflow.com'&nbsp; &nbsp; ];&nbsp; &nbsp; function randomSite() {&nbsp; &nbsp; &nbsp; &nbsp; var i = parseInt(Math.random() * sites.length);&nbsp; &nbsp; &nbsp; window.open(sites[i], '_blank');&nbsp; &nbsp; }</script>

12345678_0001

可以设置一个像这样的简单结构来执行这个&nbsp;&nbsp;<body>&nbsp;&nbsp; &nbsp; <p>Click the button to open a new tab </p>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; <button onclick="NewTab()">&nbsp;&nbsp; &nbsp; &nbsp; Open Google&nbsp; </button>&nbsp; &nbsp;<script>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; function NewTab() {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.open(&nbsp; &nbsp; &nbsp;"https://www.google.org", "_blank");&nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; </script>&nbsp;</body>&nbsp;</html> ```

陪伴而非守候

在您的randomSite()功能交换location.href = sites[i];&nbsp;中:window.open('http://' + sites[i],'_blank');也许您可以以某种方式使用 location.href 命令,我不熟悉它。但是打开一个窗口是直截了当的,如果您添加属性“_blank”,它将在新选项卡中打开。

30秒到达战场

创建一个新的HTMLAnchorElement并使用它的click方法(不是click事件):function onHeadingClicked( e ) {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; const a = document.createElement( 'a' );&nbsp; &nbsp; a.target = '_blank';&nbsp; &nbsp; a.href&nbsp; &nbsp;= getRandomUrl();&nbsp; &nbsp; a.click();}<h1 onclick="onHeadingClicked(event)">Click me</h1>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript