简体   繁体   English

附加按钮仅适用于附加到的第一个 div

[英]Appended button only works on first div appended to

I'm trying to get each button that is appened to ('avatar-container comment ng-scope'), to be fully functional.我试图让每个附加到 ('avatar-container comment ng-scope') 的按钮功能齐全。 Currently, only the top button is the button that is functional, and I'm not sure exactly why.目前,只有顶部按钮是可用的按钮,我不确定确切原因。 Here's my code :这是我的代码:

Also, I've already tried using addEventListener, but I was still running into the same problem :(.另外,我已经尝试过使用 addEventListener,但我仍然遇到同样的问题:(。

$(document).ready(function () {
var groupcomments = $('.group-comments') // Container "Group Comments" are in
$(groupcomments).ready(function () {
    function ucall(user) {
        window.open('derp.com/userid=' + user, 'popup', 'width=600', 'height=600')
    };
    if (groupcomments[0]) {
        var comments = groupcomments[0].getElementsByClassName('avatar-container comment ng-scope') // This gathers all of the comments themselves
        $.each(comments, function () { // (you know this) but, this is looping over each comment.
            var user = $(this).find('a')[0].href.toString(); 
            user = user.replace(/[^\d]/g, '')
            $(this).append('<button id=btnn>Click</button>') // using $(this) (which i assume are the comments, it appends the button to the comment)
            var btn = document.getElementById('btnn') // getting the button
            $(btn).click(function () {
                ucall(user) // when button is clicked, call ucall function. 
            })
        })
    }
})

}) })

I commented in everything that should be useful, the button being appended worked, but it being clicked does not.我评论了所有应该有用的东西,附加的按钮有效,但点击它没有。 Only on the first one appended.仅在第一个附加。 I'm just stuck right here.我只是被困在这里。

You are adding a button <button id=btnn">Click</button> inside a loop. This means that you are adding several buttons all with the same ID. So, when you call document.getElementById('btnn') , you are only getting the first match in the list of buttons with the same ID.您正在循环内添加一个按钮<button id=btnn">Click</button> 。这意味着您要添加多个具有相同 ID 的按钮。因此,当您调用document.getElementById('btnn') ,您只获得具有相同 ID 的按钮列表中的第一个匹配项。

You are only allowed to have one element with an ID.您只能拥有一个带有 ID 的元素。 IDs are unique. ID 是唯一的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM