JS事件处理程序
时间:2020-02-23 14:33:49 来源:igfitidea点击:
在本教程中,我们将学习JavaScript中的事件和事件处理。
什么是事件
事件是当我们与页面元素进行交互时发生的事情。
例如,单击按钮是一个事件,将鼠标悬停在链接上是一个事件,依此类推。
什么是事件处理程序?
这些是对象的特殊预定义JavaScript属性(文档中大多数情况下的元素),用于在事件发生时进行处理。
事件和事件处理程序的示例
假设我们在页面中有一个按钮。
当用户单击按钮时,我们会收到"点击"事件。
可以通过JavaScript中的" onclick"事件侦听器来处理此click事件。
如何添加事件处理程序?
我们可以通过向元素添加特殊属性或者通过创建脚本,然后将其附加到元素来向元素添加事件处理程序。
在HTML元素中添加事件处理程序
假设我们有一个按钮,并且希望在单击" Hello World"消息时发出警报。
解决此问题的一种方法是在按钮上添加onclick事件处理程序。
<button onclick="window.alert('Hello World');">Click Me</button>
在脚本标签中添加事件处理程序
在此,我们将JavaScript代码编写在script标签内,然后将逻辑附加到onclick事件处理程序。
<button onclick="greetings();">Click me</button>
<script>
function greetings() {
window.alert("Hello World");
}
</script>
在单独的JavaScript文件中添加事件处理脚本
在此,我们在单独的JavaScript文件中编写事件处理逻辑,然后将其包含在HTML文件中。
index.html文件
<button id="mybtn">Click me</button> <script src="/path/to/script.js"></script>
script.js文件
//get the button by id
var btn = document.getElementById("mybtn");
//attach the event handler
btn.onclick = function() {
window.alert("Hello World");
};
事件
以下是一些常见事件。
onchange
当用户更改表单中的某些内容时,将发生此事件。
例如,当用户更改选择选项时,我们可以显示警报消息。
<select onchange="window.alert('Option changed');">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
ondblclick
用户双击时发生此事件。
<button ondblclick="window.alert('hello');">Double Click Me</button>
onload
当网页完成加载时,将发生此事件。
//function to call when loading finishes
function greetings() {
window.alert("Loading complete.");
}
//attach greetings function to the onload event handler
window.onload = greetings;
onresize
调整窗口大小时,将发生此事件。
//function to call when resizing finishes
function greetings() {
window.alert("Resize complete.");
}
//attach greetings function to the onresize event handler
window.onresize = greetings;
onscroll
当用户滚动可滚动区域时,会发生此事件。
//function to call when scrolling finishes
function greetings() {
window.alert("Scrolling complete.");
}
//get textarea by id
//assuming there is a textarea having id="mytextarea"
var textarea = document.getElementById("mytextarea");
//attach greetings function to the onscroll event handler
textarea.onscroll = greetings;
onsubmit
提交表单时发生此事件。
表格HTML
<form id="myform"> <label>Username</label> <input type="text" name="username" id="username"> <input type="submit" value="Submit"> </form>
JavaScript
//get the form by id
var form = document.getElementById("myform");
//attach the onsubmit event handler
form.onsubmit = function() {
window.alert("Form submitted");
//to prevent the page from reloading
return false;
};

