gpt4 book ai didi

javascript - 当用户单击按钮时运行函数?

转载 作者:行者123 更新时间:2023-11-30 09:17:16 26 4
gpt4 key购买 nike

我正在尝试使用附加表中的附加按钮调用函数。

这是我的代码片段。

function userAction(){
window.alert("Hi");
}

var newbtn=document.createElement('button');

newbtn.setAttribute('type','button');
newbtn.setAttribute('onclick',userAction);
newbtn.setAttribute('class','btn btn-primary mt-4');
newbtn.innerHTML='Review'
tr.appendChild(newbtn);

点击下方链接获取完整代码

https://drive.google.com/file/d/1t6M5L_6tXYdGnemI8t0qlcFb93jkbx0I/view?usp=sharing

我希望它能在用户单击按钮时创建一个弹出式警报,但它似乎不起作用。这是我检查元素时的样子:

<button type="button" onclick="function userAction(){
window.alert(&quot;Hi&quot;);
}" class="btn btn-primary mt-4">Review</button>

我可能做错了什么?谢谢!

最佳答案

添加 Click Event Listener像这样而不是 setAttribute:

newbtn.addEventListener('click', () => userAction());

关于javascript - 当用户单击按钮时运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54171961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com