click() firing multiple times

2019-02-25 07:11发布

I am using a document.getElementById("val").click() to invoke a click event, but it keeps firing multiple times.

Here I add the eventHandler

try {
    //add mousedown event handler to navigation buttons
    addEventHandler(oPrevArrow, "mousedown", handlePrevDayClick);
    addEventHandler(oNextArrow, "mousedown", handleNextDayClick);
    addEventHandler(oLogout, "mousedown", handleLogoutClick);
} 
catch (err) {
}

In the click event i am performing a "auto click"

function handleNextDayClick(e) {
    e = e || window.event;
    stopEvent(e);
    document.getElementById("btn_nextday").click();
}

I need help to figure out what is making it call multiple times and a possible fix.

NB: the button that is auto-clicked calls a method in the ASP.NET Code-Behind

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-25 07:38

Usually when you have an event firing multiple times it is because the event is attached to an element more than once or the element you are auto clicking is a child of another element with the same event attached. Check to see if they are wrapped by each other and if so you will need to detect that the current target is equal to the target to make sure it only happens once. Or you can stop the event propagation.

查看更多
疯言疯语
3楼-- · 2019-02-25 07:42

try hooking it up with JQuery:

 $(document).ready(function() {
    $('#oPrevArrow').click(function() {
        $('#btn_prevday').trigger('click');
    });
    $('#oNextArrow').click(function() {
        $('#btn_nextday').trigger('click');
    });
    $('#oLogout').click(function() {
        $('#btn_logout').trigger('click');
    });
 });

This could be even more concise, depending on how your arrows and Buttons are laid out in the DOM. Potentially it could be a single line of jQuery.

Something like:

 $(document).ready(function() {
    $('.arrow').click(function() { //note css class selector
        $('this + button').trigger('click');
    });
 });
查看更多
该账号已被封号
4楼-- · 2019-02-25 07:45

It happens due to the particular event is bound multiple times to the same element.

The solution which worked for me is:

Kill all the events attached using .die() method.

And then attach your method listener.

Thus,

$('.arrow').click(function() {
// FUNCTION BODY HERE
}

should be:

$('.arrow').die("click")
$('.arrow').click(function() {
// FUNCTION BODY HERE
}
查看更多
登录 后发表回答