简体   繁体   English

我可以对else语句使用两个动作吗?

[英]Can i use two actions on an else statement?

Sorry if it's a basic question but i can't make two "actions" work on one single else if. 抱歉,如果这是一个基本问题,但是如果我不能对另一个执行两个“操作”。

I want it to say different greetings and at the same time change the background color of body based on the present hour. 我想说不同的问候,并同时根据当前时间更改主体的背景颜色。

The code works without this line: 该代码在没有这一行的情况下有效:

document.getElementById("####").style.background = '#######';

This is the code that doesn't work: 这是无效的代码:

    var today = new Date();
    var hourNow = today.getHours();
    var greeting;

    if (hourNow > 20) {
        greeting = 'Boa noite!'; document.getElementById("body").style.background = '#000000';
    } else if (hourNow > 12) {
        greeting = 'Boa tarde!';
        document.getElementById("body").style.background = '#ffffff'; 
    } else if (hourNow > 0) {
        greeting = 'Bom descanço!'; document.getElementById("body").style.background = '#121212';
    } else if (hourNow > 7) {
        greeting = 'Bom dia!'; document.getElementById("body").style.background = '#bf3d3d';
    }
    document.write(greeting);

I appreciate every help i can get! 我感谢我所能提供的一切帮助! Thank you in advanced!! 谢谢高级!!

You could use an object for the wanted parameters to change and use an array of the keys in the wanted order with a callback for changing the given values. 您可以使用一个对象来更改所需的参数,并按所需顺序使用键数组,并带有用于更改给定值的回调。

 var greetings = { 20: { greeting: 'Boa noite!', background: '#000000' }, 12: { greeting: 'Boa tarde!', background: '#ffffff' }, 7: { greeting: 'Bom dia!', background:'#bf3d3d' }, 0: { greeting: 'Bom descanço!', background: '#121212' } }, hourNow = (new Date).getHours(); [20, 12, 7, 0].some(function (hour) { if (hourNow >= hour) { // check for greater and equal document.getElementById("greeting").innerHTML = greetings[hour].greeting; document.body.style.background = greetings[hour].background; return true; // exit loop } }); 
 <div id="greeting" style="background-color: #ffffff;"></div> 

You should add an <h1> tag to your body and then set the innerText on that for the greeting. 您应该在正文中添加<h1>标记,然后在其上设置innerText作为问候语。

<!-- HTML -->
<h1 id="greeting"></h1>

// JS
var greeting = document.getElementById('greeting');

if (hourNow > 20) {
    greeting.innerText = 'Boa noite!';
    document.body.style.backgroundColor = '#000000';
}

You should put 你应该放

else if (hourNow > 7)

before 之前

else if (hourNow > 0)

Right now the last else if is unreachable 现在,如果无法到达,则最后一个

当您不提供casebreak ,可以使用switch语句并利用掉线行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM