簡體   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