繁体   English   中英

Javascript在另一个函数中设置变量?

[英]Javascript set variable from within another function?

假设我在名为“test”的函数中有一个名为“true”的变量。 然后我在一个完全不同的脚本标记中有另一个函数,我想使用我的新函数更改“true”。 我怎样才能做到这一点? 谢谢。

<script type="text/javascript">
var hello="no";
if(hello=="yes"){ 
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "Message";
  }
}
</script>

<script type="text/javascript">
function show(id) {
     $('#' + id).show();
     var hello="yes";


}
</script>

它似乎没有工作......

在您的函数中,不要使用var关键字。 这样做会在函数范围内声明一个不同的变量hello

// Earlier, you defined the variable at a higher scope here:
var hello="no";
// The function has *not* been called yet, so hello will never equal "yes" when this initially runs.
if(hello=="yes"){ 
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "Message";
  }
}

function show(id) {
  $('#' + id).show();
  // No var here!
  // the variable was defined at a higher (window) scope already with the var keyword.
  hello="yes";
}

更新:

调用onbeforeunload时,你的逻辑有问题。 除非hello == "yes" ,否则你永远不会绑定事件,它在运行时永远不会。 而是检查confirmExit()函数中的变量内容:

window.onbeforeunload = confirmExit;
function confirmExit()
{
  if (hello == "yes") {
    return "Message";
  }
}
// this will work in your case 
var hello="no";
if(hello=="yes"){
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "Message";
  }
}
function show(id) {
     $('#' + id).show();
     hello="yes";
}


// Just an small explation of how scope works in Javascript

var hello = "no"; // this has a global scope.
function showGlobal(){
alert(hello); // will alert 'no'
}

function showLocal(){
 var hello ="yes"; // hello is now a local variable. Scope is limited to the function.
 alert(hello); // will alert 'yes'. Scope is local  

}

function showLocalBlock(){

    if(condition == 'true'){
    hello = 'yes';
    }
alert(hello); // will alert yes.

}

// Closure

function ShowClosure(){
 var hello = "yes";
    function ShowInner(){
    alert(hello); // here the variable hello takes the value of the function in which it was defined.

    }  
}

暂无
暂无

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

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