【问题标题】:How can I "escape" the scope of a return statement?我怎样才能“逃避”return 语句的范围?
【发布时间】:2012-08-19 08:55:52
【问题描述】:

我需要设置一个事件处理程序,其工作是返回正在设置处理程序的函数,而不是匿名触发器处理程序本身。如何做到这一点?请看下面的代码:

if(subFormToServer())
    doSuccessDance();
else
    doErrorStuff();

function subFormToServer(thaGoods) {
  $('<iframe name="subform-target" style="display: none;"></iframe>')
    .bind('load',  function(){ return 0; }) // how to I "pass" these return statements "up" to my function or "escape" them, so to speak, so that what they're returning isn't the load/error handler functions, but actually the subFormToServer function?
    .bind('error', function(){ return 1; })
    .appendTo('body');

 $('<form method="POST" '+
          'action="http://server/formHandler.php" '+
          'target="subform-target"> '+

        '<input name=inputName              value="'+encodeURIComponent(thaGoods)+'">'+

    '</form>')[0]
    .submit();
}

【问题讨论】:

  • 即使读了两遍,我也无法理解你的问题。请考虑进一步分解代码,并可能提供类似 jsFiddle 的东西。
  • 我认为 pastebins 和 JSFs 在这里不受欢迎,因为 bin 可能会离线并使问题变得毫无价值?

标签: javascript function event-handling return


【解决方案1】:

这是不可能的。考虑一下这种情况,如果是的话:

// Assume form takes 10 seconds to respond
var x = subFormToServer(...)

// form has neither loaded nor errored yet - what does x contain?
alert(x)

你最好的选择是:

subFormToServer(thaGoods, doSuccessDance, doErrorStuff);

function subFormToServer(thaGoods, worked, didnt) {
    $('<iframe name="subform-target" style="display: none;"></iframe>')
        .on('load',  worked)
        .on('error', didnt)
        .appendTo('body');

    $('<form />', {
        method: "POST",
        action: "http://server/formHandler.php",
        target: "subform-target"
    }).append(
        $('<input />', {
            name: "inputName",
            value: encodeURIComponent(thaGoods)
        })
    ).submit()
}

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2011-01-26
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    相关资源
    最近更新 更多