javascript - 按钮的 OnClick 事件在初始化时触发?

标签 javascript html

我有两个按钮,单击时都会触发一个函数运行,但参数不同。它们应该仅在页面上存在特定元素时单击它们时触发该功能。

JS代码:

if (pageExists != null) {

  document.getElementById('button1').onclick = function(53);
  document.getElementById('button2').onclick = function(23);
}

按钮 html(除了 ID 之外,它们是相同的副本):

    <a href="nextpage.html"><button type="button" id="button1">click here</button></a>

它调用的函数将该参数存储在 LocalStorage 中,然后它应该使用 html 代码转到下一页。使用断点显示,页面加载后它会存储 53,然后存储 23。大小写和 ID 正确。

我该怎么做才能让它等到单击两个按钮之一后再执行该函数?我不能为此使用 jquery。

最佳答案

您正在调用该函数,而不是设置要调用的函数,因此当运行您的代码来设置事件处理程序时,它们会运行 function(53) ,然后将处理程序设置为该函数调用的返回值是无效的。相反,您想将其设置为一个函数。试试这个:

if (pageExists != null) {
  document.getElementById('button1').onclick = function.bind(53);
  document.getElementById('button2').onclick = function.bind(23);
}

如果由于兼容性原因而无法使用.bind(这也会更好地解释它):

if (pageExists != null) {
  document.getElementById('button1').onclick = function() {
    function(53);
  };
  document.getElementById('button2').onclick = function() {
    function(23);
  };
}

请注意,我假设您的函数实际上并不称为 function,因为这是一个保留关键字。

关于javascript - 按钮的 OnClick 事件在初始化时触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36931057/

相关文章:

javascript 文件结构 - 任何好的解决方案?

javascript - 火狐存储API : basic data save not saving

javascript - 元素闪烁

javascript - postman - 在预请求脚本中访问完整的请求主体(以计算哈希)

html - 字体系列在输出中没有改变

html - Favicon 不适用于根网站,仅在刷新后适用于特定网站

带有正负数量的 HTML 表单编号字段

javascript - 导轨 : accessing a non-instance variable in js. erb

html - 如何设置在输入时触发哪个提交按钮?

javascript - 使用 JavaScript 代码在 Google map 中添加更多具有不同位置的标记