EventListener for a class?

后端 未结 4 359
离开以前
离开以前 2021-01-17 07:15

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 don

4条回答
  •  清酒与你
    2021-01-17 07:25

    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();
      });
    });
    

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

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

    For old browsers:

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

    For new browsers:

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

提交回复
热议问题