1

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

它似乎没有工作...

4

2 回答 2

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";
  }
}
于 2012-09-24T01:41:24.020 回答
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.

    }  
}
于 2012-09-24T01:58:43.590 回答