首页 > 解决方案 > 尝试将 onclick() 函数附加到按钮时,有哪些解决问题的技巧?

问题描述

我希望我的按钮在单击时触发 PDF 文件的下载。但是,我无法让按钮在单击时触发该功能。现在,我只想要 console.log 的按钮“它有效”

我选择了正确的元素,并将类型定义为“按钮”,并且能够控制台记录按钮。但是当附加 button.onclick()= function{ console.log("it works");}; 它不会触发控制台中的 console.log。我还将 onclick 函数放入 window.onload 函数中。

 <div id="resume" class="resume">
    <button type="button" id="resume-button" class="resume-button">RESUME</button>
</div>

--JavaScript--

var button = document.querySelectorAll('.resume-button');

window.onload = function(){

button.onclick = function(){
    console.log("yay its working");
}; }

我希望控制台在单击按钮时输出“它可以工作”,但单击时没有任何反应。

标签: javascriptbuttononclick

解决方案


document.querySelectorAll返回一个 NodeList,因此您需要访问该按钮作为此 NodeList ( document.querySelectorAll('.resume-button')[0])的第一个元素

var button = document.querySelectorAll('.resume-button')[0];

button.onclick = function(){
  console.log("yay its working");
};
<div id="resume" class="resume">
    <button type="button" id="resume-button" class="resume-button">RESUME</button>
</div>

另请注意,无需将 onclick 函数分配包装到window.onload


推荐阅读