1

如何在单击时从子函数返回父函数?这是一个示例代码:

function returnFunction() {

    var output = false;

    $('a').click(function() {

       output = true;

    });

    return output;    

}

var result = returnFunction();

结果将始终为 false,因为在运行代码时未发生单击。我怎么能做到这一点呢?

我的意图是调用弹出对话框,并且我希望将所有逻辑都包含在一个可以轻松加载的函数中 - 包括确认对话框的单击事件。

在脚本的其他地方,我会这样称呼它,例如:

// Menu click triggers the dialog
$('a').click(function(e) {
    // The function displays the dialog and returns the click events of the dialog
    var result = returnFunction();
    // If result was false, we'll prevent the menu access, for example
    if (!result) {
        e.preventDefault();
    }
});

我知道 jQuery UI 对话框插件。但我现在想在没有它的情况下实现这一目标。

谢谢。

4

2 回答 2

2

An over-simplification of it is:

Everything stops (including scrolling and clicking on hyperlinks) while executing javascript. This means you cannot "pause" the script until someone clicks on a link.

The typical way of solving this is a callback function:

function my_callback(some, arguments) {
    // you can do whatever in here: an ajax load, set a global variable, change some of the page, ...
    console.log(some, arguments);
    alert(some + " " + arguments);
}

function returnFunction(callback, param) {
    var output = false;
    $('a').click(function() {
       callback(param, "world");
    });
}

returnFunction(my_callback, "hello");

demo at http://jsfiddle.net/UnBj5/

EDIT:

I did mention global variables because they are an option, but they are typically bad style. Try to use other means if possible.

If you want more help with it, provide more details of what you are trying to do.

于 2012-08-24T14:33:22.967 回答
0

尝试改用参数。将参数发送到显示警报框的函数,根据参数显示不同的弹出警报,您尝试执行的操作将不起作用,因为它基本上是一个鸡蛋问题。

于 2012-08-24T14:29:14.483 回答