没有 jQuery:
html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="./css.css">
<title>Try Out</title>
</head>
<body>
<ul>
<li>Hello There</li>
<li>General Kenobi</li>
</ul>
<script src="./js.js"></script>
</body>
</html>
CSS(无关):
body{
background-color: black;
}
ul li {
margin: 10px;
border: 1px solid blue;
color: green;
}
最后,在javascript中:
'use strict'
document.querySelector("html").onclick = handleBackgroundClick;
function handleBackgroundClick(event) {
alert("In background / html");
}
for(let li of document.querySelectorAll("ul li"))
li.onclick = handleLiClick;
function handleLiClick(event) {
alert(this.innerHTML);
event.stopPropagation();
}
点击html li → alert li text,点击其他地方 → alert 背景文本。