2017-08-23 5 views
1

最初にキャンセルを押した後にこのコードが「キャンセルしました」と表示されないのはなぜですか?setTimeoutで小さなタイムアウトで同期機能が実行されない

「hi」の表示を許可しないボックスを確認します。

<!DOCTYPE html> 
<html> 
    <body> 
    <h2>JavaScript Confirm Box</h2> 
    <button onclick="myFunction()">Try it</button> 
    <p id="demo"></p> 
    <script> 
     function myFunction() { 
     document.getElementById("demo").innerHTML = "hi"; 
     setTimeout(confirmOperation, 0, "Please, press a button!"); 
     } 
     function confirmOperation(message) { 
     var txt; 
     if (confirm(message) == true) { 
      txt = "You pressed OK!"; 
      document.getElementById("demo").innerHTML = txt; 
      return true; 
     } else { 
      txt = "You pressed Cancel!"; 
      document.getElementById("demo").innerHTML = txt; 
      setTimeout(confirmOperation, 0, "Please, press a button!"); 
      return false; 
     } 
     } 
    </script> 
    </body> 
</html> 
+0

DOMの再描画でテキストを置き換える時間を許さないconfirmOperationを直ちに実行するため – epascarello

答えて

0

遅延が0秒の関数を再帰呼び出ししています。まず第一に

document.getElementById("demo").innerHTML = txt; 
setTimeout(confirmOperation, 5, "Please, press a button!"); 
          ^^ 

function myFunction() { 
 
     document.getElementById("demo").innerHTML = "hi"; 
 
     setTimeout(confirmOperation, 0, "Please, press a button!"); 
 
    } 
 

 
    function confirmOperation(message) { 
 
     var txt; 
 
     if (confirm(message) == true) { 
 
     txt = "You pressed OK!"; 
 
     document.getElementById("demo").innerHTML = txt; 
 
     return true; 
 
     } else { 
 
     txt = "You pressed Cancel!"; 
 
     console.log(txt); 
 
     document.getElementById("demo").innerHTML = txt; 
 
     setTimeout(confirmOperation, 5, "Please, press a button!"); 
 
     return false; 
 
     } 
 
    }
<body> 
 

 
    <h2>JavaScript Confirm Box</h2> 
 

 

 
    <button onclick="myFunction()">Try it</button> 
 

 
    <p id="demo"></p> 
 

 

 
</body>

0

への変更を

document.getElementById("demo").innerHTML = txt; 
setTimeout(confirmOperation, 0, "Please, press a button!"); 
          ^^ 

例えば5ミリ秒のわずかな遅延を設定し、あなたがあなたの中で「メッセージ」を定義していないようですfunction confirmOperation(message)です。

第2に、setTimeout(...)を間違って使用しています。関数に渡す必要があり、かっこが足りません。

第3に、dom要素にイベントリスナーがありません。私はそれが役に立てば幸いhttps://jsfiddle.net/kmxr6f21/

<h2>JavaScript Confirm Box</h2> 
<button onclick="myFunction()">Try it</button> 
<p id="demo"></p> 

<script> 

function myFunction() { 
    console.log("Clicked"); 
    document.getElementById("demo").innerHTML = "hi"; 
    setTimeout(function() { 
    confirmOperation("Please, press a button!"); 
    }); 
} 

function confirmOperation(message) { 
    var txt; 
    if (message == true) { 
    txt = "You pressed OK!"; 
    document.getElementById("demo").innerHTML = txt; 
    return true; 
    } else { 
    txt = "You pressed Cancel!"; 
    document.getElementById("demo").innerHTML = txt; 
    //setTimeout(confirmOperation, 0, "Please, press a button!"); 
    return false; 
    } 
} 

</script> 

:ここ

は非かなりjsfiddle例です。

関連する問題