【问题标题】:(event.Target === document.getElementById("id")) returns false even though they are pointing at the same element(event.Target === document.getElementById("id")) 返回 false,即使它们指向同一个元素
【发布时间】:2020-04-22 03:32:57
【问题描述】:

伙计们!第一次来这里,感谢您提前阅读。

我已经动态生成了一些元素并使用事件绑定向它们添加事件,如下所示。

for(var i = 0, length = list.length || 0; i < length; i++){
    str += "<li class = 'mb-2' data-reply_id ='" + list[i].reply_id + "'>";
    str += "<div><div class = 'width100 reply_info'><span><strong>" + list[i].replyer +"</strong></span>";
    str += "<span><small>" + replyService.formatDate(list[i].reply_date) + "</small></span>";
    str += "<button class = 'basic_btn btn btn-primary' id = 'reply_modify'>modify</button><button class = 'basic_btn btn btn-primary' id = 'reply_delete'>delete</button></div>";
    str += "<div class='comment-content comment col-md-10 col-sm-9 col-12 width100'><p class = 'fn'>";
    str += list[i].reply + "</p></div></div></li>";
}
replyUL.html(str);

$("#comments").on("click", "li", function(e){
    var reply_idValue = $(this).data("reply_id");

    console.log(reply_idValue);
    console.log(e.target);    
    console.log(typeof(e.target));
    console.log("");
    console.log(document.getElementById("reply_delete"));
    console.log(typeof(document.getElementById("reply_delete")));   

    if(e.target === document.getElementById("reply_delete")){
        console.log("worked!");
        if(confirm("Are you sure?")){
            replyService.remove(reply_idValue, function(result){
            alert(result);
            showList(1);
            })
        }else{
            console.log("not working!");
    }

但问题是,(e.target === document.getElementById("reply_delete")) 返回 false, 即使 console.log(e.target);和 console.log(document.getElementById("reply_delete"));返回相同的按钮元素(当然也返回相同的类型)。

有人知道为什么会发生这种情况以及如何解决这个问题吗?

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    看起来您创建了多个具有相同 ID 的元素。不要那样做 - id 必须是唯一的。我建议改用类:

    <button class='basic_btn btn btn-primary reply_delete'>
    

    然后你可以写:if (e.target.classList.contains('reply_delete')) { ... }

    参考:Element.idElement.classList

    【讨论】:

      猜你喜欢
      • 2013-12-12
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      • 1970-01-01
      • 2017-04-08
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多