javascript - 尝试将 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");
}; }
我希望控制台在单击按钮时输出“它可以工作”,但单击时没有任何反应。
解决方案
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
推荐阅读
- java - 以给定格式将 ArrayList 数据存储到 Object 中
- xamarin - 当用户单击不滚动时如何更改所选项目
- android - 为什么 RecyclerView 中的 ConstraintLayout 在运行时会改变它的宽度设置?
- c++ - 如何修改向量向量的元素(使用自动迭代器)?
- c - C 中的默认参数和参数提升
- python-3.x - 从数据中生成随机样本
- bash - 如何远程登录到主机名和端口并执行 cp(copy) 命令以使用 bash 脚本将文件复制到当前工作目录
- firebase - 如何识别 Google Cloud 函数中的错误原因
- java - 如何通过在另一个类中调用的方法更改对象变量?
- itext7 - 如何使用 iText7 执行吊销检查?