【问题标题】:Opening a new tab on button click单击按钮打开一个新选项卡
【发布时间】:2019-09-20 21:51:38
【问题描述】:

我想使用在新选项卡中打开的按钮创建一个链接。

我目前使用的代码当前正在打开一个空白选项卡,我不确定为什么。

<div class="text text-left">

    <h2>WORK</h2>
    <h1>Title</h1>

    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam pellentesque felis ante, eu convallis sem egestas id.</p>

    <p>Etiam fermentum vestibulum hendrerit. Nam ac felis dolor ultricies varius eget vel arcu.</p>

    <button href="https://www.behance.net" onclick="window.open(this.href); return false;">View Project</button>

</div>

单击按钮后,预期结果将是打开一个新选项卡 (Behance.com) - 不是空白选项卡。

谢谢。

【问题讨论】:

标签: javascript html button hyperlink navigation


【解决方案1】:

属性href不允许在元素button上而不是添加href只需在HTML中使用data-href,在JavaScript中只需将this.href更改为this.getAttribute('data-href'),如下所示:

<div class="text text-left">

    <h2>WORK</h2>
    <h1>Title</h1>

    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam pellentesque felis ante, eu convallis sem egestas id.</p>

    <p>Etiam fermentum vestibulum hendrerit. Nam ac felis dolor ultricies varius eget vel arcu.</p>

    <button data-href="https://www.behance.net" onclick="window.open(this.getAttribute('data-href')); return false;">View Project</button>

</div>

由于权限被阻止,您无法直接运行代码。您可以在自己的项目中尝试此方法。

【讨论】:

    【解决方案2】:

    当调试这样的事情时,我喜欢做的第一件事是console.logthis.href,因为你没有得到你所期望的。这里所有的问题迹象都指向this.href。如果你这样做,你会看到它给你undefined

    您正在寻找的是window.location.href。更新您的 onclick 以反映这一点。

    https://developer.mozilla.org/en-US/docs/Web/API/Window/location

    【讨论】:

      【解决方案3】:

      this.href 无效。使用this.getAttribute('href')

      JSFiddle Demo


      但是,虽然这回答了您的问题,但这不是不是好的做法。
      正如@Sami Ahmed Siddiqui 指出的那样,href 不是按钮元素的有效属性。
      相反,您可以使用 data-* 属性,例如 data-href

      【讨论】:

      • @NathanWilson href 不允许在元素 button 上使用。相反,您可以添加data-href
      【解决方案4】:

      使用

      <a href="https://www.behance.net" target="_new" onclick="window.open(this.href); return false;">View Project</a>
      

      【讨论】:

        【解决方案5】:

        <div class="text text-left">
        
            <h2>WORK</h2>
            <h1>Title</h1>
        
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam pellentesque felis ante, eu convallis sem egestas id.</p>
        
            <p>Etiam fermentum vestibulum hendrerit. Nam ac felis dolor ultricies varius eget vel arcu.</p>
        
            <button href="https://www.behance.net" onclick="window.open(this.getAttribute('href'),'_blank')" >View Project</button>
        
        </div>

        【讨论】:

        • 对 URL 进行硬编码并不是原始发帖人的目的。
        猜你喜欢
        • 1970-01-01
        • 2016-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-30
        • 2020-12-29
        相关资源
        最近更新 更多