简体   繁体   中英

passing event to javascript function in external js

I have function which open window pop on click event. Theses function are on external js files.

$(document).ready(function() {
    $('a.cart-window').click(open);

    function open (){
        // function perform
        var loginBox = $(this).attr('href');
        return false;
    }   
});

Everything work fines. but when i re-initiate this function ( $('a.cart-window').click(open); ) in response of ajax success call to implement this function on newly generated html, it wont work. firebug shows error ( NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object ).

what just i am trying to do is that, I have lots of lengthy JS functions and give them a name like open as i show in above code and call it from anywhere so i don't need to write full code in ajax success response. Impotant Note I use $(this) in my functions and also want to pass event to function.

ajax code

function callAjax() {

$.ajax({
    url: ,
    type: "POST",
    data: 
}).done(function (msg) {

$('a.cart-window').click(open);

});

}

Try this,

(document).ready(function() {
    $('a.cart-window').on('click',function(e){open(e)});
    function open (e){
        e.preventDefault();
        // function perform
        var loginBox = $(e.currentTarget).attr('href');// you can use e.currentTarget here
        return false;
    }   
});

if you are dealing with dynamic elements, use event delegation(using event propagation) using .on()

$(document).ready(function() {
    $(document).on('click', 'a.cart-window', open);

    function open (){
        // function perform
        var loginBox = $(this).attr('href');
        return false;
    }   
});

In this case there is no need to re-initiate the event handlers for the newly updated dom.

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