1 回答

TA貢獻1812條經驗 獲得超5個贊
問題在于.load()
方法的使用,該方法可能有用,但不適用于本例。.load()
在其內部,$.ajax()
您可以使用 jQuery 向服務器發出請求。使用它來訪問服務器隨每個請求返回的玩家計數值。
將代碼分為兩個函數,一個用于獲取玩家計數,另一個用于使用動畫更新玩家計數。每當第一個函數下載了新的計數并且該計數與您已有的計數不同時,請調用第二個函數進行更新和動畫處理。
<span?class="count"?id="players"></span>
$(document).ready(function() {
? // Set starting count.
? let count = 0;
? const $players = $('#players');
? /**
? ?* Updates the player count with an animation and
? ?* saves the new player count.
? ?*/
? function updatePlayerCount(newCount) {
? ? $({?
? ? ? counter: count // Starting value, which is the last known count value.
? ? }).animate({?
? ? ? counter: newCount // Value to animate to, which is the new count value.
? ? }, {
? ? ? duration: 1000,
? ? ? easing: 'swing',
? ? ? step: function() {
? ? ? ? $players.text(Math.ceil(this.counter));
? ? ? },
? ? ? complete: function() {
? ? ? ? count = newCount; // Update the count value after the animation to compare it later again.
? ? ? }
? ? });
? }
? /**
? ?* Gets the count value from the server and?
? ?* passes it to the updatePlayerCount function
? ?* if the count has been changed.
? ?*/
? function getPlayerCount() {
? ? $.ajax({
? ? ? url: 'global_users.php',
? ? ? method: 'GET'
? ? }).done(function(newCount) {
? ? ? newCount = Number(newCount); // Makes sure that the value is a number.
? ? ? if (count !== newCount) {?
? ? ? ? updatePlayerCount(newCount); // newCount is a different value than count, so updatePlayerCount is called.
? ? ? }
? ? });
? }
? // Execute getPlayerCount every 5 seconds.
? setInterval(getPlayerCount, 5000);
});
- 1 回答
- 0 關注
- 209 瀏覽
添加回答
舉報