简体   繁体   中英

add change() event to an existing click() function without triggering the first event

I have a JQuery click() function and I need to add the change() event for another element (that must only trigger the change() event).

How can I combine it, but make this extra element only trigger one of the two events?

$('body').on('click change', '.click-1, .click-2, :checkbox, .change', function()

I added the change event and the change class. Also for the checkboxes, are they going to trigger the two events? (could it be a problem?).

Is there any way to make the element only trigger that event and not the click() ?

I just need to find a way to not repeat the same code (50 lines) twice.

EDIT: Fix (thanks to @somethinghere):

$('body').on('click change', '.click-1, .click-2, :checkbox, .change', function(event) {

    if (event.type == 'click' && $(this).hasClass( 'change' )) {
        event.preventDefault();
        event.stopImmediatePropagation();
        return;
    }

    // more code
});

A proper fix should be use click() only for the buttons.

Simple, store the function and pass the function as a parameter twice:

function yourfunctionname(e) {
   ...
}

$('body').on('click', '.click-1, .click-2', yourfunctionname)
    .on('change', ':checkbox, .change', yourfunctionname);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM