简体   繁体   English

使用 e.target 获取复选框的 id 和<label for="“…”"></label>

[英]Get id of checkbox with e.target and <label for=“…”>

I try to track the clicks on my website.我尝试跟踪我网站上的点击次数。 Therefore I use e.target.id.因此我使用 e.target.id。 When clicking on a label with for="mycheckbox" I will get the id of the label, not the checkbox.当单击带有 for="mycheckbox" 的 label 时,我将获得 label 的 ID,而不是复选框。 How can I get the for tag?如何获得 for 标签?

document.addEventListener('mousedown', function(e) {
  e = e || window.event;
  alert("checkbox with id: " + e.target.id.toString() + " checked"); //doesn't work with labels
, false);

Regards问候

You can get the for attribute by using e.srcElement.htmlFor or e.target.htmlFor .您可以使用e.srcElement.htmlFore.target.htmlFor获取for属性。

PS - for is not a tag, it is an attribute. PS - for不是标签,它是一个属性。 You can get value of any attribute by using getAttribute() .您可以使用getAttribute()获取任何属性的值。

Most probably, your lable will be the adjacent previous sibling of the input element.最有可能的是,您的lable将是输入元素的相邻上一个兄弟。 In this case, you can use previousElementSibling.id to get the id of the lable .在这种情况下,您可以使用previousElementSibling.id来获取lable的 id。 Below is a snippet explaining the same -下面是一个解释相同的片段 -

 document.addEventListener('mousedown', function(e) { e = e || window.event; //Check if we have clicked on an input - if(e.target.outerHTML.includes("input")){ alert(e.target.previousElementSibling.id); } }, false);
 <lable for="check" id="lable">Check1</lable> <input type="checkbox" id="check" name="check"> <br> <br> <lable for="check2" id="lable2">Check2</lable> <input type="checkbox" id="check2" name="check2">

In this way, you can implement the same solutions with multiple inputs.通过这种方式,您可以使用多个输入实现相同的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM