javascript确认功能确定并取消返回相同的结果 [英] javascript confirm function ok and cancel returns same result

查看:59
本文介绍了javascript确认功能确定并取消返回相同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

result()方法中,每当涉及到其他部分时,我都需要退出函数callthis().

Here in result() method, whenever it comes to else part, I need to get out of the function callthis().

它不应该执行kumar()函数.

这可能吗? 其实我可以这样使用

Is this possible? Actually, I can use like this

if(result)          //if this method is true, it will come inside
{
    kumar();
}

但这不是我想要的.从result()方法返回false时,它应该退出循环function calthis()

But this is not I want. while returning false from result() method, it should get out of the loop function calthis()

function calthis()
{
  var i=1;
  if(i==0)
  {
    alert("inside if");
  }
  else
  {
    alert("inside else");
    result();
    kumar();
  }

}
function result()
{
  var res = confirm("are you wish to continue");
  if(res==true)
  {
    return true;
    alert("inside if result");
  }
  else
  {
    return false;
  }
}
function kumar()
{
  alert("inside kumar");
}

<a href="" onclick="calthis();">Click here</a>

推荐答案

这里有很多错误.

首先,if (result)仅测试变量result是否包含真实值,它实际上并未调用该函数.如果要测试该函数的返回值,则需要

First, if (result) just tests whether the variable result contains a truthy value, it doesn't actually invoke the function. If you want to test the return value of the function, you need

if (result()) {

第二,您不了解return 立即离开当前功能.您无法进行有意义的操作:

Secondly, you're not understanding that return immediately leaves the current function. You can't meaningfully do this:

if(res==true)
{
return true;
alert("inside if result");
}

无法达到alert.遇到return true时,该函数立即返回.

That alert cannot be reached. The function returns immediately when return true is encountered.

第三,要提早退出callThis,您只需要提早return.由函数callThis有条件地返回;这取决于函数.您不能在result函数内部强制向下返回.如果调用该函数的上下文不能强制返回该函数.不能由result函数的内部来确定是否应运行kumar.您不能直接影响调用方法中的执行路径. result所能做的就是返回某些内容,或者(在这种情况下,不必要地复杂)接受回调并有条件地执行它.

Thirdly, to exit callThis early, you simply need to return early. It's up to the function callThis to conditionally return; you cannot force a return from down inside the result function. A function cannot forcibly return out if the context that called it. It's not up to the internals of the result function to determine if kumar should run. You cannot influence the path of execution in the calling method directly. All result can do is return something, or (needlessly complex in this case) accept a callback and conditionally execute it.

仅从callThis中的return:

function calthis()
{
  var i=1;
  if(i==0)
  {
    alert("inside if");
  }
  else
  {
    alert("inside else");
    if (!result()) return;
    kumar();
  }

}

这篇关于javascript确认功能确定并取消返回相同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆