The onclick
event in JavaScript lets you as a programmer execute a function when an element is clicked.
JavaScript中的onclick
事件可讓您作為程序員在單擊元素時執行功能。
按鈕Onclick示例 (Button Onclick Example)
<button onclick="myFunction()">Click me</button><script>function myFunction() {alert('Button was clicked!');}
</script>
In the simple example above, when a user clicks on the button they will see an alert in their browser showing Button was clicked!
.
在上面的簡單示例中,當用戶單擊按鈕時,他們將在瀏覽器中看到一條警告,顯示Button was clicked!
。
動態添加onclick (Adding onclick dynamically)
The onclick
event can also be programmatically added to any element using the following code in the following example:
在以下示例中,還可以使用以下代碼將onclick
事件以編程方式添加到任何元素:
<p id="foo">click on this element.</p><script>var p = document.getElementById("foo"); // Find the paragraph element in the pagep.onclick = showAlert; // Add onclick function to elementfunction showAlert(event) {alert("onclick Event triggered!");}
</script>
注意 (Note)
It’s important to note that using onclick we can add just one listener function. If you want to add more, just use addEventListener(), which is the preferred way for adding events listener.
請務必注意,使用onclick只能添加一個偵聽器功能。 如果要添加更多內容,只需使用addEventListener(),這是添加事件偵聽器的首選方法。
In the above example, when a user clicks on the paragraph
element in the html
, they will see an alert showing onclick Event triggered
.
在上面的示例中,當用戶單擊html
的paragraph
元素時,他們將看到顯示onclick Event triggered
的警報。
防止默認動作 (Preventing default action)
However if we attach onclick
to links (HTML’s a
tag) we might want prevent default action to occur:
但是,如果我們將onclick
附加到鏈接(HTML a
標記),我們可能希望防止發生默認操作:
<a href="https://guide.freecodecamp.org" onclick="myAlert()">Guides</a><script>function myAlert(event) {event.preventDefault();alert("Link was clicked but page was not open");}
</script>
In the above example we prevented default behavior of a
element (opening link) using event.preventDefault()
inside our onclick
callback function.
在上面的示例中,我們在onclick
回調函數中使用event.preventDefault()
防止a
元素(打開鏈接)的默認行為。
MDN
MDN
其他資源 (Other Resources)
jQuery .on() Event Handler Attachment
jQuery .on()事件處理程序附件
翻譯自: https://www.freecodecamp.org/news/javascript-onclick-event-explained/