请问为什么不代理的时候会报错?

来源:19-2 事件-代码演示

最和缓的阳光

2018-03-26

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <meta charset="utf-8">
</head>
<body>
    <div id="div1">
      <a href="http://imooc.com" id="link1">imooc</a>
      <a href="http://imooc.com" id="link2">imooc</a>
      <p>imooc</p>
      <a href="http://imooc.com" id="link3">imooc</a>
      <a href="http://imooc.com" id="link4">imooc</a>
      <p id="p1">激活</p>
      <p id="p2">取消</p>
    </div>
    <div id="div2">
        <p id="p3">取消</p>
        <p id="p4">取消</p>
    </div>

    <script type="text/javascript">

      function bindEvent(elem, type, selector, fn){
        if (fn === null) {
          fn = selector
          selector =null
        }
        elem.addEventListener(type, function(e){
          var target
          if (selector) {
            // 代理
            target = e.target
            // console.log(target)
            if (target.matches(selector)) {
              fn.call(target, e)
            }
          } else {
            //不是代理
            fn(e)
          }
        })
      }


      var div1 = document.getElementById('div1')
      bindEvent(div1, 'click', 'a', function(e){
        e.preventDefault()
        console.log(this.innerHTML)
      })

      
      var p1 = document.getElementById('p1')
      bindEvent(p1, 'click', function(e){
        console.log(p1.innerHTML)
      })

    </script>
</body>
</html>

SyntaxError: 'function(e){ console.log(p1.innerHTML) }' is not a valid selector

写回答

1回答

双越

2018-03-27

你忽略了一个细节。将 if (fn === null) { 改为 if (fn == null) { 试试。=== 和 == 在这里使用一定要注意。

0
4
众颖
回复
最和缓的阳光
没有fn的时候,fn的值为undefined,是基本数据类型,但null是引用数据类型,所以fn和null不可能完全相等,因为类型就不同。但是使用==的时候就没有影响了,==会进行类型转换,所以null和undefined都可以,两者都会被转换成false
2018-03-27
共4条回复

BAT大牛带你横扫初级前端JavaScript面试(第二版)

BAT高级前端工程师亲授,结合真实面试题,提高面试成功几率

4268 学习 · 817 问题

查看课程