最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Prevent click on label from triggering child button - Stack Overflow

programmeradmin2浏览0评论

When setup like this, clicking on a label that has a child button triggers button's onclick event:

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

When setup like this, clicking on a label that has a child button triggers button's onclick event:

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

is there a way to prevent this?

Share Improve this question asked Nov 12, 2020 at 11:49 Guga FigueiredoGuga Figueiredo 2925 silver badges19 bronze badges 2
  • 2 That is just a pattern you should avoid to begin with; mon accessibility guidelines explicitly advise against nesting such interactive elements which have their own functionality into labels. – C3roe Commented Nov 12, 2020 at 11:57
  • 1 granted.. I'll work on a better design in the future. – Guga Figueiredo Commented Nov 12, 2020 at 12:21
Add a ment  | 

5 Answers 5

Reset to default 3

You can add preventDefault for labels and keep the existing code:

document.querySelector("label").addEventListener("click", function(event) { 
    event.preventDefault();
}, false);

Add for attribute to label.

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

You can put the button outside the label

<label>Label</label>
<button onclick="fireButton()">Button</button>

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>

Here's an approach in CSS which also disables triggering button's :active state when clicking on label. Overriding label's onClick event does not do that.

label {
  pointer-events: none;
}
    
button {
  pointer-events: initial;
}
发布评论

评论列表(0)

  1. 暂无评论