繁体   English   中英

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

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

我尝试跟踪我网站上的点击次数。 因此我使用 e.target.id。 当单击带有 for="mycheckbox" 的 label 时,我将获得 label 的 ID,而不是复选框。 如何获得 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);

问候

您可以使用e.srcElement.htmlFore.target.htmlFor获取for属性。

PS - for不是标签,它是一个属性。 您可以使用getAttribute()获取任何属性的值。

最有可能的是,您的lable将是输入元素的相邻上一个兄弟。 在这种情况下,您可以使用previousElementSibling.id来获取lable的 id。 下面是一个解释相同的片段 -

 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">

通过这种方式,您可以使用多个输入实现相同的解决方案。

暂无
暂无

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

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