函数原型方法中的'e'参数不起作用

时间:2012-03-19 08:49:03

标签: javascript parameters event-bubbling

我想使用e参数来停止javascript泡泡

这是我的代码:

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);
    });
});
然而,它不起作用,萤火虫告诉我“e未定义”

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

改变这个:

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

对此(你忘了把e放在你的功能中)

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

答案 1 :(得分:0)

在通话现场

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

范围内没有名为e的符号;因此,浏览器抱怨。由于符号没有神奇地出现,您想告诉浏览器eclick处理程序中传递的第一个参数:

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

您知道作为传递给处理程序的参数,因为docs表示您的handler将被赋予eventObject - 但是当然,您可以根据需要自由命名参数。

答案 2 :(得分:0)

让它更漂亮。

顺便说一句,使用$(this).attr('id')会浪费资源。你可以像我在代码belove中那样简单地获取id。

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

method中,您应该使用以下内容扩展您的代码:

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