自动页面刷新后,单击功能不起作用

时间:2014-12-29 12:29:14

标签: javascript jquery html page-refresh

我使用Javascript每25秒刷新一次页面。但是,在页面刷新之前,另一个用于点击功能的Javascript工作正常,而在页面刷新之后它不起作用。

HTML:

 <div id="refreshOnline">
    <div id="refreshData">
    //Set of Functions
     <a target="_blank" href="http://example.com/startgame.php?gname='.$key['gameName'].'&player='.$_SESSION["uname"].'&type=t20" class="btn btn-primary btn-sm popup-game" id="popup-game" >Play Now!</a>
  </div>
 </div>

使用Javascript:

   <script type="text/javascript"> 
   //Script to refresh Div
   function show_data()
   {
    $('#refreshOnline').load('main.php #refreshData');
   }
    setInterval('show_data()', 25000);

   //Script to oprn link in new window
    $('#popup-game').click(function (event) {
    event.preventDefault();
    alert("Working");
     window.open($(this).attr("href"), "popupWindow","width=600,height=600,scrollbars=yes");
   });
</script>

在刷新之前,链接会在新窗口中打开,而在执行刷新脚本后,链接会在新选项卡中打开,而不是在新窗口中打开。

3 个答案:

答案 0 :(得分:2)

代码:

$('#popup-game').click(...

将单击处理程序绑定到代码运行时存在的#popup-game元素。如果该元素是#refreshOnline的子元素,则在刷新#refreshOnline时将替换该元素,因此该元素的新版本将不具有单击限制。您可以使用委托事件处理程序:

$('#refreshOnline').on('click', '#popup-game', function(event) {
  event.preventDefault();
  alert("Working");
  window.open($(this).attr("href"), "popupWindow","width=600,height=600,scrollbars=yes");
});

这实际上将处理程序绑定到#refreshOnline,但是当发生单击时,jQuery会自动检查它是否在与第二个参数中的选择器匹配的子元素上,如果匹配则仅调用您的函数。

有关详细信息,请参阅the .on() doco

答案 1 :(得分:0)

这是因为点击处理程序未分配给新内容。更改内容后再次设置它们:

<script type="text/javascript"> 
//Script to refresh Div
function show_data()
{
  $('#refreshOnline').load('main.php #refreshData');
  setClickers();
}

function setClickers(){
  //Script to oprn link in new window
  $('#popup-game').click(function (event) {
    event.preventDefault();
    alert("Working");
    window.open($(this).attr("href"), "popupWindow","width=600,height=600,scrollbars=yes");
  });
}

$(function(){
  setClickers();
  setInterval('show_data()', 25000);
});
</script>

答案 2 :(得分:0)

每次刷新div的内容时都应注册click事件。

相关问题