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

时间:2012-09-24 01:35:47

标签: javascript

假设我在名为“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>

它似乎无法正常工作......

2 个答案:

答案 0 :(得分:4)

在您的功能中,请勿使用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";
  }
}

答案 1 :(得分:0)

// 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.

    }  
}