防止标签点击触发子按钮

3
当以这种方式设置时,点击具有子按钮的标签会触发按钮的onclick事件:

function fireButton() {
  console.log("Button fired!");
}
<label>Label
  <button onclick="fireButton()">Button</button>
</label>

有没有办法防止这种情况发生?


2
这只是一个你应该避免的模式;常见的无障碍性指南明确建议不要将具有自身功能的交互元素嵌套在标签中。 - CBroe
1
承蒙允许,我将来会在设计方面做得更好。 - Guga Figueiredo
5个回答

3

为label添加for属性。

function fireButton() {
  console.log("Button fired!");
}
<label for=''>Label
  <button onclick="fireButton()">Button</button>
</label>


对于与其后代的ID相关联的属性。如果您不想关联它,则将其设置为空白。 - Yuvraj Mule
1
这对我很有帮助!利用内置功能简单而有效,即使我的设计不佳,正如@CBroe在评论中所述,它值得重构。https://dev59.com/n77pa4cB1Zd3GeqPsSMS#IhbsnYgBc1ULPQZFouYS - Guga Figueiredo
你设计得很好,详细阐述了问题。 :-) - Yuvraj Mule

2
您可以将按钮放在标签外面。
<label>Label</label>
<button onclick="fireButton()">Button</button>

2
您可以为标签添加preventDefault,同时保留现有的代码:
document.querySelector("label").addEventListener("click", function(event) { 
    event.preventDefault();
}, false);

1

You could use a different tag e.g <span> rather than the label But if you really need to use the <label>, you should prevent the default behaviour of the label onclick() like so:

function fireButton(){
//add actions here
}

function preventDefault(event){
  event.preventDefault()
}
<label onclick="preventDefault(event)">Label
  <button onclick="fireButton()">Button</button>
</label>


如果我也传递事件,那么我可以在fireButton()的主体中添加那行代码,对吧? - Guga Figueiredo
不,将其添加到fireButton()中不会影响标签的行为。这意味着当您单击标签时,按钮单击仍将被触发。因此,它必须在标签的单击事件上。@GugaFigueiredo - ibrahim s

1
这里有一种 CSS 方法,可以在单击标签时禁用触发 button:active 状态。覆盖 labelonClick 事件无法做到这一点。
label {
  pointer-events: none;
}
    
button {
  pointer-events: initial;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接