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 に答える