12

Chrome ブラウザで私のコードを確認してください。更新を押すと、2 つのオプションが表示されます。

  1. このページを離れて
  2. このページにとどまります

2. このページにとどまるボタンをクリックすると、カスタム関数displayMsg()をアクティブにする必要があります

誰でも私に解決策を提供できますか?

<script type="text/javascript">
function displayMsg() {
    alert('my text..');
}
</script>
<script type="text/javascript">
window.onbeforeunload = function(evt) {
  var message = 'Please Stay on this page and we will show you a secret text.';
  if (typeof evt == 'undefined') {
      evt = window.event;
  }       
  if (evt) {
      evt.returnValue = message;
      return message;
  }
  trace(evt);
} 
</script>
4

3 に答える 3

7

変数の変更をリッスンするタイマーを使用します。

var vals=0;
function displayMsg() {
    alert('my text..');
}
window.onbeforeunload = function evens(evt) {
var message = 'Please Stay on this page and we will show you a secret text.';
  if (typeof evt == 'undefined') {
      evt = window.event;
  }       
    timedCount();
    vals++;
  if (evt) {
      evt.returnValue = message ;
      return message ;
  }
  trace(evt);
} 

function timedCount()
{
t=setTimeout("timedCount()",100);
if(vals>0)
{
    displayMsg();
    clearTimeout(t);
}
}
于 2012-05-16T12:43:04.990 に答える
5

onbeforeunloadとイベントの組み合わせを使用してonunload、前者でタイマーを設定し、後者でそれをクリアできます。

var showMsgTimer;

window.onbeforeunload = function(evt) {
    var message = 'Please Stay on this page and we will show you a secret text.';
    showMsgTimer = window.setTimeout(showMessage, 500);

    evt = evt || window.evt;
    evt.returnValue = message;

    return message;
}

window.onunload = function () {
    clearTimeout(showMsgTimer);
}

function showMessage() {
    alert("You've been trolled!");
}

これはonunload、ユーザーがページにとどまることを選択したときにイベントが発生しないためです。

于 2012-05-16T10:56:01.937 に答える
1

これらのコード行を使用してください。正しく動作します。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
    <script type="text/javascript">
    $(function(){
    $(window).bind('beforeunload', function(){
      return 'Your Data will be lost :(';
     });
    });
    </script>
于 2014-07-07T06:55:23.573 に答える