一个类的EventListener? [英] EventListener for a class?

查看:94
本文介绍了一个类的EventListener?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个引用ID的EventListener,它工作良好,唯一的问题是,我至少有十几个该EventListener需要引用的地方,所以我不想有很多相同但有脚本的脚本一个不同的ID。是让EventListener引用我可以在所有需要它的地方使用的类的方法。
谢谢

I have an EventListener that references an Id and it works well, the only problem is that i have at least a dozen places where this EventListener needs to reference so i dont want to have a dozen scripts that are all the same but have a different Id. Is therea way to have the EventListener that references a class that i could use in all the places i need it. Thanks

JAVASCRIPT:

JAVASCRIPT:

document.getElementById("chartJump").addEventListener("click", function (e) { e.preventDefault() });

HTML:

<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenuGraphOne">
    <!--DROPDOWN MENU-->
    <li role="presentation"><a role="menuitem" tabindex="-1" id="chartJumpOne" href="#graphOneChart">Chart</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" id="tableJumpOne" href="#graphOneData">Data</a></li>
</ul>


推荐答案

是,使用类。每个元素都应该有一个共同的类。有了jQuery,您就可以这样做:

Yes, using classes. Every element should have a common class. And with jQuery you can do this way:

$(document).ready(function () {
  $(".className").click(function (e) {
    e.preventDefault();
  });
});

获取有关 $。click() $。ready() 。当您添加了 jquery 的问题时,我给出了jQuery解决方案。

Get more info about $.click() and $.ready(). As you have added jquery, I have given the jQuery solution.

使用香草JavaScript,您可以通过两种方式实现相同的功能:

Using vanilla JavaScript, you can achieve the same functionality in two ways:

对于旧的浏览器:

window.onload = function () {
  list = document.getElementsByClassName("className");
  for (var i = 0; i < list.length; i++) {
    list[i].addEventListener("click", function (e) {
        e.preventDefault();
    });
  }
};

对于新浏览器:

window.onload = function () {
  list = document.querySelectorAll(".className");
  for (var i = 0; i < list.length; i++) {
    list[i].addEventListener("click", function (e) {
        e.preventDefault();
    });
  }
};

这篇关于一个类的EventListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆