javascript 动态添加dom元素,添加类名,添加自定义属性,添加点击事件,
·
//获取父节点
let farther =document.getElementById("farther")
//跟换属性值 假如跟换src的属性值
farther.src = 'image.jpg'
//创建节点
let son = document.createElement('div')
//为子节点更换类名/添加类名
son.className = 'newClassValue'
//为字节点添加自定义 属性名和值
son.setAttribute('myAttribute','myAttributeValue')
//为子节点添加点击事件
son.onclick = myfun
//向父元素 添加子节点,注意不要加引号""
farther.appendChild( son ) //添加新元素到尾部。
farther.insertBefore( son ) //添加新元素到开始位置
//获取自定义属性的值
let son = document.getElementById('son').getAttribute('myAttribute')
window.open('rul') // 打开新窗口
window.close() //关闭当前窗口
动态添加节点、
let father = document.getElementById('father')
for(let i=0;i<4;i++){
let child = document.createElement('div')
chile.onclick = myfun
father.appendChild(child)
}
//最后这个father的父元素就有了 4个子节点,可以根据后台返回的数据进行动态添加
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)