简体   繁体   中英

The 'e' parameter in function's prototype method doesn't work

I want use e parameter to stop javascript bubble

here is my code:

function test(){}
test.prototype.method=function(parameter,e){
    console.log(parameter)
    e.preventDefault();
}
var t=new test();

$(function(){
    $('.node').click(function(){
       t.method($(this).attr('id'),e);
    });
});

however,it doesn't work,the firebug tell me the "e is not defined"

How can I solve this problem?

Change this :

$(function(){
    $('.node').click(function(){
       t.method($(this).attr('id'),e);
    });
});

To this (you forgot to put the e in your function)

$(function(){
    $('.node').click(function(e){
       t.method($(this).attr('id'),e);
    });
});

At the call site

t.method($(this).attr('id'),e);

there is no symbol named e in scope; therefore, the browser complains. Since symbols do not magically appear, you want to tell the browser that e is the first argument passed in your click handler:

$('.node').click(function(e){ // ADDED FORMAL PARAMETER
   t.method($(this).attr('id'),e);
});

You know that there will be a parameter passed to the handler because the docs say that your handler will be given an eventObject -- but of course you are free to name the parameter as you prefer.

Made it a bit prettier.

Using $(this).attr('id') is a waste of resources by the way. You can simply get the id like I did in the code belove.

$(function(){
    $('.node').on('click',function(e) {
       t.method(this.id,e);
    });
});

In your method you should expand your code with the following:

if (e.preventDefault)
    e.preventDefault();
else
    e.stop();

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