有没有什么方法可以使用元素的ID或类在函数内捕获事件

时间:2018-11-21 15:13:14

标签: javascript jquery html ajax

我试图使用函数中的ID捕获按钮的onclick事件,然后尝试console.log的值!但是我认为由于事件捕获代码位于函数内部,因此无法检测到事件何时触发!有没有解决的办法!谢谢!

window.onload = xyz;

function xyz() {
click();
 
  }
 function click() {
    var x = document.querySelector("#btn");
    x.addEventListener("click", myfunction);
    console.log(x);}

function myfunction() {
  document.querySelector(".example").style.backgroundColor = "red";
  return 1;
}
<h2 class="example">A heading with class="example"</h2>

<p>Click the button to add a background color to the first element in the document with class="example".</p>

<button id="btn">Try it</button>

2 个答案:

答案 0 :(得分:1)

您可以将点击功能转换为IIFE:

function insertLogin($myro, $mysqli)
(function click() {
  var x = document.querySelector("#btn");
  x.addEventListener("click", myFunction);
  console.log(x);
})()

function myFunction() {
  document.querySelector(".example").style.backgroundColor = "red";
  return 1;
}

还要在调用函数时确保大小写匹配

答案 1 :(得分:0)

您可以像这样使用上的jQuery。

$("#btn").on( "click", myFunction);

function myFunction() {
  document.querySelector(".example").style.backgroundColor = "red";
  return 1;
}

这可以。

我也没有检查这是否是您示例中的唯一问题,但是似乎您在名为myfunction => myFunction

的函数名称中存在错误
x.addEventListener("click", myFunction);