使用jQuery

时间:2016-01-28 22:05:19

标签: javascript jquery

我有以下代码:

var compliments = {
    complimentLocation: '.compliment',
    currentCompliment: '',
    complimentList: {
        'morning': mycompliments.morning,
        'afternoon': mycompliments.afternoon,
        'evening': mycompliments.evening
    },
    updateInterval: mycompliments.interval || 30000,
    fadeInterval: mycompliments.fadeInterval || 4000,
    intervalId: null
};

compliments.updateCompliment = function () {

    var _list = [];

    var hour = moment().hour();

    if (hour >= 3 && hour < 12) {
        _list = compliments.complimentList['morning'].slice();
    } else if (hour >= 12 && hour < 17) {
        _list = compliments.complimentList['afternoon'].slice();
    } else if (hour >= 17 || hour < 3) {
        _list = compliments.complimentList['evening'].slice();
    } else {
        Object.keys(compliments.complimentList).forEach(function (_curr) {
            _list = _list.concat(compliments.complimentList[_curr]).slice();
        });
    }

    var _spliceIndex = _list.indexOf(compliments.currentCompliment);

    if (_spliceIndex !== -1) {
        _list.splice(_spliceIndex, 1);
    }

    var _randomIndex = Math.floor(Math.random() * _list.length);
    compliments.currentCompliment = _list[_randomIndex];

    $('.compliment').updateWithText(compliments.currentCompliment, compliments.fadeInterval);

}

compliments.init = function () {

    this.updateCompliment();

    this.intervalId = setInterval(function () {
        this.updateCompliment();
    }.bind(this), this.updateInterval)

}


function functionToLoadFile(){
    jQuery.get('js/mycompliments.js', function(data) {

        var compliments = {
            complimentLocation: '.compliment',
            currentCompliment: '',
            complimentList: {
                'morning': mycompliments.morning,
                'afternoon': mycompliments.afternoon,
                'evening': mycompliments.evening
            },
            updateInterval: mycompliments.interval || 30000,
            fadeInterval: mycompliments.fadeInterval || 4000,
            intervalId: null


        };

        console.log(compliments);

        setTimeout(functionToLoadFile, 5000);
    });
    compliments.reload = function (compliments) {

        compliments.updateCompliment(compliments);
    }
}
setTimeout(functionToLoadFile, 5000);

使用最后一个函数functionToLoadFile我正在加载一个外部文件并每5秒重置compliments的值。

到目前为止一切正常(赞美获得新值),但我没有将新值传递给updateCompliment,触发其功能并更新前端的值。

我错过了什么?

更新

这是在pageload上加载的外部文件,每5秒后加载一次:

var mycompliments = {
    morning: [
        'Good morning, handsome!',
        'Enjoy your day!',
        'How was your sleep?'
    ],
    afternoon: [
        'etc'
    ],
    evening: [
        'weiik'
    ]
}

3 个答案:

答案 0 :(得分:0)

变化:

compliments.updateCompliment = function () {

为:

compliments.updateCompliment = function (compliments) {

并在functionToLoadFile()中将ajax调用更改为:

jQuery.get('js/mycompliments.js', function(data) {

    var compliments1 = {
        complimentLocation: '.compliment',
        currentCompliment: '',
        complimentList: {
            'morning': mycompliments.morning,
            'afternoon': mycompliments.afternoon,
            'evening': mycompliments.evening
        },
        updateInterval: mycompliments.interval || 30000,
        fadeInterval: mycompliments.fadeInterval || 4000,
        intervalId: null
    };

    console.log(compliments1);
    compliments.updateCompliment(compliments1);
    setTimeout(functionToLoadFile, 5000);
});

但最重要的是阅读一些关于类概念的教程。

答案 1 :(得分:0)

不要加载JavaScript文件并直接从中读取数据。这是一种不好的做法。将 mycompliments.js 文件转换为 JSON ,然后使用get()加载它。然后使用回调中的data参数实际填充数据。

我还建议你使用短绒。

<强> JS / mycompliments.json

{
    "morning": [
        "Good morning, handsome!",
        "Enjoy your day!",
        "How was your sleep?"
    ],
    "afternoon": [
        "etc"
    ],
    "evening": [
        "weiik"
    ]
}

<强> main.js

/*jslint browser: true, nomen: true*/
/*global jQuery, moment*/

(function () {

    "use strict";

    // Function to do UI updates
    function updateUI(compliments) {

        var _list = [],
            hour = moment().hour(),
            _spliceIndex,
            _randomIndex;

        if (hour >= 3 && hour < 12) {
            _list = compliments.complimentList.morning.slice();
        } else if (hour >= 12 && hour < 17) {
            _list = compliments.complimentList.afternoon.slice();
        } else if (hour >= 17 || hour < 3) {
            _list = compliments.complimentList.evening.slice();
        } else {
            Object.keys(compliments.complimentList).forEach(function (_curr) {
                _list = _list.concat(compliments.complimentList[_curr]).slice();
            });
        }

        _spliceIndex = _list.indexOf(compliments.currentCompliment);

        if (_spliceIndex !== -1) {
            _list.splice(_spliceIndex, 1);
        }

        _randomIndex = Math.floor(Math.random() * _list.length);
        compliments.currentCompliment = _list[_randomIndex];

        jQuery(".compliment")
            .updateWithText(compliments.currentCompliment, compliments.fadeInterval);

    }

    // Function to deal with updating compliments
    function updateCompliments() {
        jQuery.get("js/mycompliments.json", function (data) {

            var jsonData,
                compliments;

            // Parse data
            jsonData = JSON.parse(data);

            // Update with gotten data
            compliments = {
                complimentLocation: ".compliment",
                currentCompliment: "",
                complimentList: {
                    "morning": jsonData.morning,
                    "afternoon": jsonData.afternoon,
                    "evening": jsonData.evening
                },
                updateInterval: jsonData.interval || 30000,
                fadeInterval: jsonData.fadeInterval || 4000,
                intervalId: null
            };

            updateUI(compliments);

            // Do this again in a little while
            setTimeout(updateCompliments, compliments.updateInterval);
        });
    }

    // Run update at DOM load
    document.addEventListener("DOMContentLoaded", updateCompliments);

}());

答案 2 :(得分:0)

您的compliments.updateCompliment(compliments);未被调用,因为它已包含在compliments.reload函数中。

您可以通过调用全局compliments.updateCompliment函数并将compliments作为参数来使其工作。

然而,需要指出的一些事情是

  1. var compliments被重复定义,因此被functionToLoadFile
  2. 中的一个阴影
  3. setTimeout(functionToLoadFile, 5000);在另一个setTimeout(functionToLoadFile, 5000);内被调用,好像functionToLoadFile不仅每隔5秒被调用一次,但在文件加载后,它会触发另一个setTimeout检查一下。
  4. 你可以做的是

    1. 删除了第一个var compliments
    2. 替换compliments.updateCompliment = function () { var updateCompliment = function(compliments) {
    3. setTimeout(functionToLoadFile, 5000);之后将console.log替换为window.updateCompliment(compliments)
    4. 我猜你也可以删除compliments.reload功能。
    5. 您可以详细了解javascript here