如何选择在 DOM 之后渲染的 HTML 元素

问题描述 投票:0回答:1

我想选择OKBTN

let main = document.querySelector("#main");
let okBtn = document.querySelector("#ok");

function myAlert(title,msg,icon){
    let card = "";
    card += `<div class="card">
        <img src="${icon}.jpg">
        <h1>${title}</h1>
        <p>${msg}</p>
        <button id="ok">OK</button>
    </div>`;
    
    main.innerHTML = card;
}

okBtn.addEventListener("click", function(){
main.style.display = "none";
});

myAlert("标题","MSG","图标")

显示错误: 未捕获的类型错误:无法读取 null 的属性(读取“addEventListener”) 在imggal.html:88:5

javascript dom modal-dialog jquery-selectors addeventlistener
1个回答
0
投票

因为标签一开始不存在,所以返回

undefined
我建议将代码放入函数中,然后将事件标记属性挂钩到函数

let main = document.querySelector("#main");

function myAlert(title,msg,icon){
    let card = "";
    card += `<div class="card">
        <img src="${icon}.jpg">
        <h1>${title}</h1>
        <p>${msg}</p>
        <button id="ok" onclick="handleClick(e)">OK</button>
    </div>`;
    
    main.innerHTML = card;
}

const handleClick = e => {
main.style.display = "none";
});
© www.soinside.com 2019 - 2024. All rights reserved.