【问题标题】:Button inside hyperlink div超链接 div 内的按钮
【发布时间】:2020-05-16 04:35:38
【问题描述】:

我有一个带有超链接的元素。里面还有按钮,应该触发它们的按钮动作,而不触发超链接。

演示代码:

<a href="element.html">
 <div class="element_card">
   This is an card for an element with an hyperlink over the card.
    <button type="button" onclick="like_element()">
      Like the element but do not trigger the hyperlink.
    </button>        
 </div>
</a>

如何禁用按钮的超链接或取消事件,使按钮区域仅触发按钮的onclick功能而不触发超链接。

【问题讨论】:

  • 您将需要 javascript,但是到目前为止您尝试了什么,您有一些 JS 代码吗?它不工作吗?
  • 您的 HTML 无效。按钮不能是锚点的后代
  • @j08691 为什么不呢?块级锚类似于 div。 OP 只需要在处理按钮的点击事件时停止传播。
  • @GetSet 我没有制定规则
  • 从技术上讲它可以工作,但不遵循 html 规范。一种解决方法是使用包装div 与您的abutton 标记作为孩子,然后使用css 定位使buttons 看起来好像它们在a

标签: javascript html


【解决方案1】:

您可以使用event.stopPropagation() 阻止点击沿链向上传播。

【讨论】:

    【解决方案2】:

    您可以使用event.stopPropagation() 来防止当前事件在冒泡阶段进一步传播。

    https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

    【讨论】:

      【解决方案3】:

      看看这是否适合你。

      &lt;a&gt;标签的onclickhref属性的默认行为是执行onclick,然后只要onclick不返回false就跟随href,取消事件(或事件未被阻止) 看看这是否适合你。

      Answer

      <a href="element.html">
       <div class="element_card">
         This is an card for an element with an hyperlink over the card.
          <button type="button" onclick=" return like_element()">
            Like the element but do not trigger the hyperlink.
          </button>        
       </div>
      </a>
      

      【讨论】:

        【解决方案4】:

        在 href javascript:void(0) 中使用这个

        function like_element(){
          console.log('working....!')
        }
        .element_card{
        background-color: green;
        }
        <a href="javascript:void(0)">
         <div class="element_card">
           This is an card for an element with an hyperlink over the card.
            <button type="button" onclick=" return like_element()">
              Like the element but do not trigger the hyperlink.
            </button>        
         </div>
        </a>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-03-29
          • 1970-01-01
          • 2011-11-04
          • 2020-08-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多