![](/img/trans.png)
[英]how to get element id on click without any inline function call in javascript?
[英]How can I get the ID of an HTML element in a JavaScript function without passing any parameters?
如何在不傳遞任何參數的情況下獲取 HTML 中 JavaScript function 元素的 ID?
我有一個 HTML 元素:
<input type="text" id="exampleInput" value="0" onkeypress="exampleFunction()">
從 JavaScript 開始,我想更改 HTML 元素的值。
function exampleFunction() {
}
是否可以在不將 ID 作為參數傳遞的情況下實現此目的?
您可以像this
將其傳遞給您的 function:
function exampleFunction(e) { console.log(e); // element console.log(e.id); // id e.value = 'new value'; // change value }
<input type="text" id="exampleInput" value="0" onkeypress="exampleFunction(this)">
或者,更好的是,改用addEventListener
:
document.getElementById('exampleInput').addEventListener('keypress', function (e) { console.log(e.target); // element console.log(e.target.id); // id e.target.value = 'new value'; // change value });
<input type="text" id="exampleInput" value="0">
您可以像this
將元素傳遞到 function 中。
function exampleFunction(element) { console.log(element.value); }
<input type="text" id="exampleInput" value="0" onkeypress="exampleFunction(this)">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.