在函数内添加换行符

Add line break inside a function

我在函数中添加换行符时遇到问题。该函数显示日期和时间。我需要在第一行显示日期,第二行显示时间。我已经检查了所有相关的答案。我曾尝试使用 \n, br, join("\n"),试图在我的函数中创建 br 元素,但不幸的是它没有用。这是我的一段代码:

function getTime(a)
{ 
  var d;
  if(a) {
    d = new Date(a);
  } else {
    d = new Date();
  }
  return ('0' + d.getDate()).slice(-2) + '.'+
         ('0' + (d.getMonth() + 1)).slice(-2) + '.' + 
         (d.getYear() + 1900) + ' ' + // here instead of space I need to add a line break in order to display time on a new line 
         ('0' + d.getHours()).slice(-2) + ':' +
         ('0' + d.getMinutes()).slice(-2) + ':' + 
         ('0' + d.getSeconds()).slice(-2) + '.' + 
         d.getMilliseconds();
}

请给我提示如何解决这个问题。 非常感谢您!

您可以添加换行符:

function getTime(a)
{ 
  var d;
  if(a) {
    d = new Date(a);
  } else {
    d = new Date();
  }
  return ('0' + d.getDate()).slice(-2) + '.'+
         ('0' + (d.getMonth() + 1)).slice(-2) + '.' + 
         (d.getYear() + 1900) + '\n' + // here instead of space I need to add a line break in order to display time on a new line 
         ('0' + d.getHours()).slice(-2) + ':' +
         ('0' + d.getMinutes()).slice(-2) + ':' + 
         ('0' + d.getSeconds()).slice(-2) + '.' + 
         d.getMilliseconds();
}

console.log(getTime())

或者如果你想在内部标记 html 中添加 <br>

    function getTime(a)
    { 
      var d;
      if(a) {
        d = new Date(a);
      } else {
        d = new Date();
      }
      return ('0' + d.getDate()).slice(-2) + '.'+
             ('0' + (d.getMonth() + 1)).slice(-2) + '.' + 
             (d.getYear() + 1900) + ' <br> ' + // here instead of space I need to add a line break in order to display time on a new line 
             ('0' + d.getHours()).slice(-2) + ':' +
             ('0' + d.getMinutes()).slice(-2) + ':' + 
             ('0' + d.getSeconds()).slice(-2) + '.' + 
             d.getMilliseconds();
    }

document.querySelector('.test').innerHTML = getTime()
<div class='test'></div>

如果您处理 html 标记 <br> 标记是显示回车符的正确方式 return。