[英]click function doesnot work after auto page refresh
我每25秒使用Javascript刷新一次頁面。但是在頁面刷新之前,另一個用於單擊功能的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>
刷新前,鏈接在新窗口中打開,而刷新腳本執行后,鏈接在新選項卡中而不是新窗口中打開。
編碼:
$('#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會自動檢查它是否在與第二個參數中的選擇器匹配的子元素上,並且僅在匹配時調用您的函數。
有關更多信息,請參見.on()
doco 。
這是因為單擊處理程序未分配給新內容。 更改內容后,請再次設置它們,如下所示:
<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>
每次刷新div的內容時,都應該注冊click事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.