简体   繁体   English

Javascript - 使用参数引用全局函数的匿名函数中的闭包 - 我如何使用preventDefault?

[英]Javascript - closure in anonymous function referencing a global function using arguments - how do i use preventDefault?

In the following code, where would I use preventDefault ? 在以下代码中,我将在哪里使用preventDefault I have been testing it to make it work but have not found a good way to cancel the default submit action. 我一直在测试它以使其工作,但还没有找到一个取消默认submit操作的好方法。 Which function needs to be capture the event object? 哪个函数需要捕获事件对象?

Here is the code: 这是代码:

f_name = 'someFunc' ;
f_args(1,2,3) ;

if(element.addEventListener) {
element.addEventListener('submit',(function(name,args,element) {
    return function() {
        window[name].apply(element,args) ;
    }
})(f_name,f_args,element)
,false) ; }

Assuming you want to preventDefault on only some event handlers, you would use preventDefault() inside the callback that you use to handle a specific event. 假设您只想在某些事件处理程序上preventDefault() ,您可以在用于处理特定事件的回调中使用preventDefault() In your example, this would the global function represented by the name argument which would be the someFunc global function. 在您的示例中,这将是由name参数表示的全局函数,它将是someFunc全局函数。

If you wanted to do it for all event handlers (which doesn't make a lot of sense to me), then you'd do it in your code right before or after you call window[name] . 如果你想为所有事件处理程序(对我来说没有多大意义)这样做,那么你在调用window[name]之前或之后就可以在代码中执行它。

f_name = 'someFunc';
f_args = [1, 2, 3];
if (element.addEventListener) {
    element.addEventListener('submit', (function (name, args, element) {
        return function (e) {
            // here 
            e.preventDefault();
            window[name].apply(element, args);
        };
    })(f_name, f_args, element), false);
}

Your handler function will be called with the event as a parameter 将使用事件作为参数调用您的处理函数

return function(evt) {
    evt.preventDefault();
    window[name].apply(element,args) ;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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