jQuery $(“.class”).click(); - multiple elements, click event once

前端 未结 18 1693
借酒劲吻你
借酒劲吻你 2020-11-29 00:01

I have multiple classes on a page of the same name. I then have a .click() event in my JS. What I want to happen is the click event only happen once, regardless of multiple

18条回答
  •  佛祖请我去吃肉
    2020-11-29 00:33

    Try making use of the .off() handler:

    $(function () {
        $(".archive-link").click(function (e) {
            var linkObj = $(this);
            var cb = $("#confirm-modal");
            cb.find(".modal-body").append("

    Warning message.

    "); cb.modal('show'); cb.find(".confirm-yes").click(function () { $(this).off(); //detach this event //ajax call yada yada.. }

    I attach a click event handler on an OK modal button to act on click event of the object with class .archive-link.

    On the first click, the event fires only on that .archive-link object that I asked the function to act on (var linkObj). But when I click the same link the second time and hit OK on the modal, the event fires on every object that has .archive-link that I clicked before.

    I used the solutions above but unfortunately did not work. It was when I called .off() within the modal OK button click function that the propagation stopped. I hope this helps.

提交回复
热议问题