我现在可能...,但是为什么当我的页面加载时这段代码会记录 hello x2,而单击 LI 元素时却什么也没有?它应该记录单击的元素名称。如果我将“hello”更改为 e.target,它会记录 HTMLDocument?!
谢谢你。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
window.onload = function(){
var list = document.getElementById("listan");
list.addEventListener("touchstart", elementClicked(event), false);
list.addEventListener("click", elementClicked(event), false);
}
function elementClicked(e) {
console.log("hello");
if(e.target && e.target.nodeName == "LI") {
console.log(e.target.nodeName);
}
}
</script>
<style>
* {
list-style: none;
margin: 0;
padding: 0;
box-sizing: border-box;
}
li {
width: 90%;
background: darkblue;
color: #eee;
margin: 10px auto;
padding: 15px;
border: 1px solid black;
text-align: center;
font-family: calibri;
cursor: pointer;
}
ul {
background: green;
padding: 10% 0;
}
</style>
</head>
<body>
<ul id="listan">
<li>apa</li>
<li>häst</li>
<li>ko</li>
<li>elefant</li>
<li>lejon</li>
<li>zebra</li>
<li>myrslok</li>
<li>grävling</li>
</ul>
</body>
</html>