【问题标题】:What does this function do?这个函数有什么作用?
【发布时间】:2017-07-25 10:31:53
【问题描述】:

我在一个网站上找到了这段代码, 我想知道这个功能是什么,做什么。 我知道 PHP、HTML、CSS 和 JavaScript, 但是我还没有学过 JQUERY 和 AJAX。我特别需要知道他们将东西放入颜色数组中的程序,它是随机的,还是有模式:

$('#onehour_next').css('backgroundColor', colors[(hours == 23 ? 0 : hours+1)]);

function doStuff()
        {       
            current = new Date();
            hours = current.getHours();
            minutes = 59 - current.getMinutes();
            seconds = 59 - current.getSeconds();

            onehour.innerHTML = prettyTime(0, minutes, seconds);

            if (colors.length === 0 || current.getSeconds() === 0)
                init();

            $('#onehour').css('backgroundColor', colors[hours]);
            $('#onehour_next').css('backgroundColor', colors[(hours == 23 ? 0 : hours+1)]);

            setTimeout(doStuff, 1000);
        }

【问题讨论】:

  • colors 数组看起来像是在此函数之外的某个地方创建的,只是在这里使用。在此函数中,没有任何内容被附加/附加到 colors 数组。
  • "but I haven't learned JQUERY and AJAX" - 这里有最小的 jQuery,没有 AJAX。 "I especially need to know the routine they follow to put stuff in the colors array" - 此代码没有将任何内容放入 colors。该变量在其他地方定义/填充。你到底在问这个代码是什么?当您调试此代码时,它的行为与您的预期有何不同?
  • 你们需要看完整的代码吗?
  • 我们需要确切地知道您在问什么以及与该问题相关的代码。在更新您的答案之前,请查看此资源:stackoverflow.com/help/how-to-ask
  • 但是如果你不懂 jQuery 并且你正在使用 jQuery,我的建议是去学习 jQuery。 api.jquery.com

标签: javascript jquery css


【解决方案1】:

代码为一天中的每个小时设置不同的颜色。

数组colors 没有在这段代码中定义,但大概它在一个列表中包含24 种不同的颜色。列表中的第一种颜色将在晚上 11 点到 11:59 之间使用,然后在午夜使用第二种颜色,依此类推,直到晚上 10 点到 10:59 之间使用第 24 种颜色。


要解释代码的工作原理,您需要查看每个小段。

  • hours == 23 在问“现在是 23 点吗?(即晚上 11 点)”
  • 0 只是数字零
  • hour + 1 比当前时间高一小时。
  • question ? answer1 : answer2 基本上说“如果问题为真,则使用 answer1。如果为假,则使用 answer2”
  • 所以(hours == 23 ? 0 : hours+1) 本质上的意思是“将当前时间四舍五入到一天中的下一个小时”,并且将是一个介于 0 和 23 之间的值
  • colors[n] 表示“查找列表颜色中的第 n 个值”。请注意,0 是第 1 项,1 是第 2 项,依此类推。
  • $('#onehour_next') 查找 ID 为 onehour_next 的 HTML 元素
  • .css 根据接下来的两个值设置该元素的 CSS
  • 'backgroundColor' 表示正在设置该元素的背景颜色
  • 所以我们从colors[(hours == 23 ? 0 : hours+1)]得到的值将被设置为元素onehour_next的背景色

【讨论】:

    猜你喜欢
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    • 2013-10-21
    • 1970-01-01
    相关资源
    最近更新 更多