javascript - 有什么方法可以使用元素的 id 或类来捕获函数内部的事件

标签 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>

最佳答案

您可以将点击函数变成 IIFE:

(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>

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

关于javascript - 有什么方法可以使用元素的 id 或类来捕获函数内部的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53415071/

相关文章:

javascript - 在 ajax 处理期间,当我们在弹出窗口外单击时,不应关闭弹出窗口

javascript - 在不使用 ID 或类的情况下使用 jQuery 修改 CSS

html - Facebook 共享抓取工具未注册 al : tags

javascript - 自定义 HttpInterceptor - 如何返回无法解析的 Observable?

c# - 如何使用 webclient 在 C# 中下载图像并使用 Javascript 从 aspx 页面获取图像

javascript - 防止绝对位置元素粘在可滚动 div 内

jquery - .change 未按预期工作

javascript - Safari 删除表单标签

javascript - 单击浏览器滚动条关闭弹出窗口

html - 我的主容器在使用 flexbox 时没有覆盖整个页面,即使我尝试居中也坐在左边