情之无殇 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日

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan