如果在锚元素中单击按钮,如何忽略锚

How to ignore anchor if button is clicked within the anchor element

我有这样一种情况,点击图片会将用户定向到某个 link,但按下图片中显示的按钮会 运行 一个 javascript 方法反而。但是,我无法阻止页面在按下按钮时重定向到某个link(单击按钮时javascript方法也是运行)。

我发现按钮不能嵌套在锚元素中,并尝试将按钮也包裹在表单中,但没有成功。

有谁知道解决这个问题的方法吗?

代码中的基本逻辑如下所示

<a href="an item description link">
    <img src="an item image"/>
    <form style="display: inline" action="html_form_action.asp" method="get">
        <button type="button" id="add-btn" class="add-cart" onclick="quick_add()">+</button>
    </form>
</a>

在此先感谢您的帮助!

一种直接的验证方法是将按钮叠加在 link 上。这要求 link 和按钮位于同一个包含元素中,并且它们都使用 position: absolute:

HTML

<div class="box">
  <a href="http://example.com">
    <img src="http://placehold.it/300x200">
  </a>
  <button>AAAAA</button>
</div>

CSS

.box {
  box-sizing: content-box;
  width: 300px;
  height: 200px;
  border: thin solid black;
}

.box > a {
  display: block;
  position: absolute;
}

.box > button {
  position: absolute;
}

在 CodePen 上查看它的实际效果:http://codepen.io/millimoose/pen/avYLjQ

该按钮将自动堆叠在前面的 link 之上。 (这是指定的行为。)它会在点击被传递到下面的元素之前处理点击。

也就是说,这个解决方案有一些缺点。你必须给容器一个固定的大小;它不能自动调整大小以适合其内容,因为它的内容在渲染流程之外。这也意味着除非您再次明确设置它们的大小,否则它们不会自动填充它们的父框。