情之无殇 2021-10-14 16:10 采纳率: 100%
浏览 67
已结题

js在构造函数中定义的dom元素无法使用this调用

构造函数如下

 constructor(id){

        this.init()
        //获取父容器的dom节点
        this.box = document.querySelector(id)
        this.picbox = this.box.querySelector(".image-box")
        this.indexbox = this.box.querySelector(".index_box")
        this.index = 1
    }

调用如下

copyPic(){
       //实现复制队首,队尾的两个图
        const imagebox = document.querySelector(".image-box")
        //const first = imagebox.firstElementChild.cloneNode(true)
        const first = this.picbox.firstElementChild.cloneNode(true)
      //报错说这里的this.picbox没有firstElementChild这个方法
    }   

浏览器就会报错如下

img

疑惑点

  • 上面的这种在方法内获取dom元素是可行的
  • 但是使用构造函数中定义的 this.picbox却不行?
    const imagebox = document.querySelector(".image-box")
    const first = imagebox.firstElementChild.cloneNode(true)
    
  • 请教一下这个原因是什么??
  • 写回答

4条回答 默认 最新

  • 李筱宝 2021-10-14 16:26
    关注

    document 结构发来, 或者你检查一下你的 id 元素下的层次结构

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 10月22日
  • 已采纳回答 10月14日
  • 创建了问题 10月14日

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常