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/