for for in 给已有的li绑定click事件生成新的li也有click事件

想要给已有的li元素绑定一个click事件,点击生成新的li元素,并且新的li元素也要有click事件

 

//不能用for循环给每个li绑定click事件 因为这样的话 后面新生成的li就没有click事件


//即使用下面的获取dom元素方法 具有实时性 也不能给新生成的li绑定clcik事件   这两个方法是 实时的 HTMLCollection 不能直接forEach循环
let ali1 = oul.getElementsByClassName('li') 
let ali2 = oul.getElementsByTagName('li')


//不是 实时的 但是 NodeList 可以直接使用forEach
let ali3 = document.querySelectorAll('.li')
let ali4 = document.getElementsByName('li')

方法:要用事件代理
//事件代理
commmentUl.onclick = function (e) {
// console.log(e.target)
let target = e.target
if(target.tagName.toLowerCase()=='a'){//点击回复按钮 出现回复框
form = target.parentNode.lastElementChild
console.log(form)
formDisplay = getStyle(form, 'display')
if (formDisplay == 'none') {
form.style.display = 'block'
form.children[0].setAttribute('autofocus', true)
} else {
form.style.display = 'none'
}

}
if(target.type=='reset'){//取消按钮
target.parentNode.style.display = 'none'
}
if(target.type=='button'){//回复按钮 发表评论
let content = target.parentNode.children[0].value
let news_id = target.parentNode.getAttribute('news-id')
let parent_id = target.parentNode.getAttribute('comment-id')
let that = target
if (!content) {
message.showError('评论内容不能为空')
return
}
let data = {
content,
news_id,
parent_id
}
$.ajax({
url: '/news/' + news_id + '/comments/',
type: 'POST',
data: JSON.stringify(data)
})
.success(function (res) {
// console.log(this)
if (res.errno == '0') {
// console.log(res.data)
let li = `



  • avatar
    ${ res.data.author }

    ${ res.data.content }


    ${ res.data.parent.author }




    ${ res.data.parent.content }


    ${ res.data.update_time }

    回复

    news-id="${ res.data.news_id }">




  • `
    $(commmentUl).prepend(li)
    that.parentNode.style.display = 'none'

    } else if (res.errno == '4101') {
    message.showError('用户未登录')
    setTimeout(function () {
    window.location.href = '/user/login/'
    }, 1000)
    }
    })
    .error(function () {
    message.showError('服务器错误,请重试')
    })
    }
    }
    for循环过程中增加新元素:
    let arr=[1,2,3]
    for(let i =0;i
    if(i==0)arr[0+3]=4
    console.log('本次循环i的值:'+i)
    }
    本次循环i的值:0
    本次循环i的值:1
    本次循环i的值:2
    本次循环i的值:3
    let arr=[1,2,3]
    for(let i =0,len=arr.length;i
    if(i==0)arr[0+3]=4
    console.log('本次循环i的值:'+i)
    }
    //在循环初始化时候 len=3,即使在循环过程中arr长度改变,len也不会变了
    本次循环i的值:0
    本次循环i的值:1
    本次循环i的值:2

    for in循环
    let obj = {name:'wl',age:21}
    for(let i in obj){
    if(i == 'name')obj['sex'] = 'man'
    console.log(obj[i])
    }
    'wl'
    21
    //不会输出'man' 因为for in 循环在循环开始前计算obj一次 之后即使在循环过程中obj新增也不会遍历到新增的
    //如果在循环过程中删除已有的未遍历的属性 也不会遍历到

    你可能感兴趣的:(for for in 给已有的li绑定click事件生成新的li也有click事件)