-2

重複の可能性:
ページの自動更新

このオンとオフのスイッチをオンラインで見つけたので、それを使用してページを更新したいと考えています。ユーザーが「オン」をクリックすると、5 秒ごとにページが更新されます。クリックすると停止します。助けてください。これが私がこれまでに持っているものです:

<style>



body{
font-family:Verdana, Geneva, sans-serif;
font-size:14px;}

.left{
float:left;
width:120px;}

#ajax{
float:left;
width:300px;
padding-top:5px;
font-weight:700;
}

.clear{clear:both;}

</style>

</head>

<body>


</a></div>
<div id="container">


 <div class="left" id="1"></div>
 <div id="ajax"></div>
  <div class="clear"></div>

  <script type="text/javascript">

    $('#1').iphoneSwitch("on", 
     function() {
       $('#ajax').load('on.html');
      },
      function() {
       $('#ajax').load('off.html');
      },
      {
        switch_on_container_path: 'iphone_switch_container_off.png'
      });
  </script> 
4

2 に答える 2

0

次のような単純なタイムアウト JavaScript 関数を使用しない理由は次のとおりです。

<script type="text/JavaScript">
    var timeoutPeriod = 5000;
    function timedRefresh(timeoutPeriod) {
        setTimeout("location.reload(true);",timeoutPeriod);
    }

</script>

オンスイッチがクリックされたときにのみこれを実行するロジックを追加できます。

于 2012-09-26T23:04:37.507 に答える
0

次のように、ページの更新を有効または無効にできます。

var refreshTimer;

$('#button').iphoneSwitch("on", 
    function() {
        refreshTimer = setTimeout(function(){ location.reload(true); }, 5000);
    },
    function() {
        clearTimeout(refreshTimer);
    },
    {
        switch_on_container_path: 'iphone_switch_container_off.png'
    }
);

ajax を使用して HTML をリロードする場合は、次のようなものを使用できます (setInterval を使用):

var refreshTimer;

function ajaxReload()
{
    $.ajax .. etc
}

$('#button').iphoneSwitch("on", 
    function() {
        refreshTimer = setInterval(ajaxReload, 5000);
    },
    function() {
        clearInterval(refreshTimer);
    },
    {
        switch_on_container_path: 'iphone_switch_container_off.png'
    }
);

編集

この例のページでは、リロードはデフォルトで無効になっています。ユーザーがボタンを使用して有効にすると、無効になるまでそのままになります。

var refreshTimer;

function enableTimer()
{
    refreshTimer = setTimeout(function(){ location.reload(true); }, 5000);
    window.location.hash = "#autoreload";
}

function disableTimer()
{
    clearTimeout(refreshTimer);
    window.location.hash = "";
}

$(function() {

    $('#button').iphoneSwitch(
        (window.location.hash == "#autoreload" ? "on" : "off"), 
        enableTimer, 
        disableTimer
    );

    if (window.location.hash == "#autoreload")
        enableTimer();
});
于 2012-09-26T23:13:52.947 に答える