javascript中onclick失效

在帮新人解决问题时无意间发现了这个问题,记录下来给大家分享一下。

请问,下面代码存不存在错误?

    <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
ο–959o–111
n–110n–110
c–99c–99
l–108l–108
i–105i–105
c–99c–99
k–107k–107
问题找到了,这个 o 有问题。大家如果碰到的话可以留意下。没事儿还能给队友埋俩个坑。

这个bug还可以这么玩,溜了溜了

	a["οnclick"] = function() {
		console.log(1)
	}
	b["onclick"] = function() {
		console.log(2)
	}

如果有更方便的写法欢迎来讨论,让我们一起有条不紊的持续进步。
喜欢的话不妨点个小小的赞与关注,您的赞与关注将是我源源不断的前进动力

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值