To create real interactivity on a website, you need events — these are code structures that listen out for things happening to the browser, and then allow you to run code in response to those things. The most obvious example is the click event, which is fired by the browser when the mouse clicks on something. To demonstrate this, try entering the following into your console, then clicking on the current webpage:
document.querySelector(‘html‘).onclick = function() { alert(‘Ouch! Stop poking me!‘); }
There are many ways to attach an event to an element. Here we are selecting the HTML element and setting its onclick
handler property equal to an anonymous (i.e. nameless) function that contains the code we want to run when the click event occurs.
Note that
document.querySelector(‘html‘).onclick = function() {};
is equivalent to
var myHTML = document.querySelector(‘html‘); myHTML.onclick = function() {};
It‘s just shorter.
时间: 2024-10-11 23:12:35