Javascript Dom按钮onclick函数在页面加载上工作的原因是什么?
嗨,我是js和html新手, 我正试图通过js在html上添加按钮,并在按钮点击时尝试显示警报消息 这是我的密码Javascript Dom按钮onclick函数在页面加载上工作的原因是什么?,javascript,html,Javascript,Html,嗨,我是js和html新手, 我正试图通过js在html上添加按钮,并在按钮点击时尝试显示警报消息 这是我的密码 topobutton=document.createElement("button"); topobutton.innerHTML="Topo"; topobutton.value="Topo"; topobutton.type="button"; topobutton.id="Topo"; topobutton.style.margin="2px";
topobutton=document.createElement("button");
topobutton.innerHTML="Topo";
topobutton.value="Topo";
topobutton.type="button";
topobutton.id="Topo";
topobutton.style.margin="2px";
document.body.appendChild(topobutton);
topobutton.onclick=showMap("topo");
function showMap(mapname){
alert(mapname)};
当页面重新加载时,它会显示警告消息,并在按钮上单击“不响应为什么?” 编辑
您正在调用函数,而不是添加引用/事件侦听器
topobutton.onclick=()=>{showMap(“topo”)}
//或
topobutton.onclick=function(){showMap(“topo”)}
//或
addEventListener('click',function(){showMap(“topo”)});