簡體   English   中英

Javascript函數可在本地服務器上運行,但不能在線運行

[英]Javascript Function Works on Local Server but not Online

因此,我有一個可以在本地服務器上運行的javascript游戲,但是一旦我將其放到網上,其中一項功能就會停止工作。 它可能與我為高分存儲的Cookie的權限有關。 有人可以指出什么可能是錯的。

    //Save Highscore if score is greater
 function saveScore() {
     loadScore();
     if (score > highscore) {
         var date = new Date();
         date.setMonth(date.getMonth() + 5);
         var expires = "; expires=" + date.toGMTString();
         document.cookie = "score=" + score + expires + "; path=/";
     }
 }

 //Load High Score
 function loadScore() {
     var cookiearray = document.cookie.split(';');
     for (var i = 0; i < cookiearray.length; i++) {
         var name = cookiearray[i].split('=')[0];
         var value = cookiearray[i].split('=')[1];
         if (name == "score") {
             //alert("Score Found!");
             highscore = value;
         }
     }
     return highscore;
 }

 //Lost game function
 function Lost() {
     saveScore();
     loadScore();
     var lost = document.getElementById("lost");
     var hs = document.getElementById("hs");
     lost.style.visibility = "visible";
     postscore.innerHTML = score;
     hs.innerHTML = highscore;
     lost.addEventListener('click', function (event) {
         window.location.reload();
     });
 }

根據您的評論,我猜測您已經隨着時間的推移修改了代碼,但是由於必須擁有一個cookie,因此一直保存着它。 在您的代碼示例中,如果cookie不存在,則永遠不會在使用它之前分配highscore 您應該具有一些在頁面加載時運行的函數,該函數查找cookie,如果不存在,則將起始狀態初始化為已知值。

此外,我建議采用面向對象的方法可能更可靠。 特別是,我將創建一個用於cookie處理的專用對象(可正確處理cookie不存在的情況)以及一個單獨的游戲對象。

來自MDN -Cookie處理程序的示例

var docCookies = {
  getItem: function (sKey) {
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!sKey || !this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: /* optional method: you can safely remove it! */ function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

將游戲元素作為對象的一種潛在實現,將其加載到使用上述cookie處理程序的立即調用函數中。

(function(cookieHandler) {
    // Game constructor
    var Game = function(cookieHandler) {
        this.init(cookieHandler);
    };

    // initializes the game variables, sets up and binds the event handlers
    Game.prototype.init = function(cookieHandler) {
       this.scoreCookie = 'score';
       this.score = 0;
       this.highScore = this.loadScore();
       this.cookieHandler = cookieHandler;
       this.lostElem = document.getElementById("lost");
       this.postScoreElem = null; // don't see this defined anywhere
       this.highScoreElem = document.getElementById("hs");

       this.setUpHandlers()
           .bind();
    };

    // create handlers for the events
    Game.prototype.setupHandlers = function() {
        this.lostHandler = this.lost.bind(this);
        return this;
    };

    // bind the handlers to events
    Game.prototype.bind = function() {
        // there should probably be a binding for some event
        // to invoke the lost handler (lostHandler)
        this.lostElem.addEventListener('click', function (event) {
            window.location.reload();
        });
    };

    // save the current score, if higher than the current high score, to
    // the game cookie
    Game.prototype.saveScore = function() {
        if (this.score > this.highScore) {
            var date = new Date();
            date.setMonth(date.getMonth() + 5);
            this.cookieHandler.setItem(this.scoreCookie, score, date, '/');
        }
    };

    // retrieves the high game score from the cookie, initializes it to zero
    // if there is no cookie.
    Game.prototype.loadScore = function () {
        this.highScore = 0;
        if (this.cookieHandler.hasItem(this.scoreCookie)) {
            this.highScore = parseInt(this.cookieHandler.getItem(this.scoreCookie,10);
        }
    };

    // when the game is lost, update the high and save the current score
    // if it is a new high score.  Signal that the game was lost.            
    Game.prototype.lost = function() {
        this.loadScore();
        this.saveScore();
        this.lostElem.style.visibility = "visible"
        // this.postScoreElem.innerHTML = score;
        this.highScoreElem.innerHTML = highscore;
    };

    var game = new Game(docCookies);
)(docCookies);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM