[英]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.htmlFor
或e.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.