在帮新人解决问题时无意间发现了这个问题,记录下来给大家分享一下。
请问,下面代码存不存在错误?
<div id="a" style="width: 200px;height: 300px;background: #00FF00;">单击变红色</div>
<div id="b" style="width: 200px;height: 300px;background: blue;">双击变黄色</div>
<script>
let a = document.getElementById("a")
let b = document.getElementById("b")
a.οnclick = function() {
this.style.background = "red"
}
b.onclick = function() {
this.style.background = "yellow"
}
</script>
大家可以新建一个html文件将代码直接粘贴进body里尝试一下。
a的单击事件是不被触发的,而b的可以。
这里我们做个打印验证一下两个div是否都有onclick方法。
console.log("a", a.hasOwnProperty("οnclick")) // false
console.log("b", b.hasOwnProperty("onclick")) // false
恩?怎么可能都没有呢?那我换种法子。
console.log("a", "οnclick" in a) // false
console.log("b", "onclick" in b) // true
哦吼,有问题。让我们仔细看看。
console.log("_________div.a________")
String("οnclick").split("").forEach(el => {
console.log(String(el) + "--" + String(el).charCodeAt())
})
console.log("_________div.b________")
String("onclick").split("").forEach(el => {
console.log(String(el) + "--" + String(el).charCodeAt())
})
打印的结果为:
_div.a | _div.b |
---|---|
ο–959 | o–111 |
n–110 | n–110 |
c–99 | c–99 |
l–108 | l–108 |
i–105 | i–105 |
c–99 | c–99 |
k–107 | k–107 |
问题找到了,这个 o 有问题。大家如果碰到的话可以留意下。没事儿还能给队友埋俩个坑。 |
这个bug还可以这么玩,溜了溜了
a["οnclick"] = function() {
console.log(1)
}
b["onclick"] = function() {
console.log(2)
}
如果有更方便的写法欢迎来讨论,让我们一起有条不紊的持续进步。
喜欢的话不妨点个小小的赞与关注,您的赞与关注将是我源源不断的前进动力