簡體   English   中英

如何訪問活動元素值

[英]how can I access active element value

我嘗試獲取活動元素id(現在關注元素),但是它不返回任何值,但是當我直接在控制台中編寫代碼時,它返回活動元素id

document.querySelector("button").onclick = function(){
console.log(document.activeElement.id);
}

此代碼完成

document.activeElement.onclick = function(){
console.log(document.activeElement.id);
}

如果要使用您在回調中單擊的元素,請使用this

document.querySelector('button').onclick = function() {
  console.log(this.id);
}

點擊事件會將按鈕作為活動元素。 如果需要單擊按鈕之前處於活動狀態的內容,則需要偵聽在失去焦點之前觸發的mousedown。

 document.querySelector("button").addEventListener("mousedown", function () { console.log("mousedown", document.activeElement.id); }) document.querySelector("button").addEventListener("click", function () { console.log("click", document.activeElement.id); }) document.querySelector("button").addEventListener("mouseup", function () { console.log("mouseup", document.activeElement.id); }) 
 <a href="#" id="a1">a1</a> <a href="#" id="a2">a2</a> <button id="TheButton">Test</button> <a href="#" id="a3">a3</a> <a href="#" id="a4">a4</a> 

JavaScript event.target獲取事件目標元素


document.querySelector("button").onclick = function(e)

  console.log(e.target.id);
}

如果要使用活動元素,例如焦點元素

document.querySelector("button").onclick = function(){
console.log(document.activeElement.id);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM