javascript
JavaScript Onclick事件解释
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/
總結
以上是生活随笔為你收集整理的JavaScript Onclick事件解释的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: javascript脚本_使用脚本src
- 下一篇: 做梦梦到鸡死好不好