警报返回为未定义

时间:2018-08-24 18:01:43

标签: javascript undefined alert

我正在尝试在计时器显示的时间显示警报。

function Stopwatch(elem) {
  var time = 0;
  var offset;
  var interval;

  function update() {
    if (this.isOn) {
    time += delta();
  }

  elem.textContent = timeFormatter(time);
}

function delta() {
  var now = Date.now();
  var timePassed = now - offset;

  offset = now;

  return timePassed;
}

function timeFormatter(time) {
  time = new Date(time);

  var minutes = time.getMinutes().toString();
  var seconds = time.getSeconds().toString();
  var milliseconds = time.getMilliseconds().toString();

  if (minutes.length < 2) {
    minutes = '0' + minutes;
  }

  if (seconds.length < 2) {
    seconds = '0' + seconds;
  }

  while (milliseconds.length < 3) {
    milliseconds = '0' + milliseconds;
  }

  return minutes + ' : ' + seconds + ' . ' + milliseconds;
  }

  this.start = function() {
    interval = setInterval(update.bind(this), 10);
    offset = Date.now();
    this.isOn = true;
  };

  this.stop = function() {
    clearInterval(interval);
    interval = null;
   this.isOn = false;
  };

  this.reset = function() {
    time = 0;
    update();
  };

  this.isOn = false;
  }

  var timer = document.getElementById('timer');
var toggleBtn = document.getElementById('toggle');
var resetBtn = document.getElementById('reset');

var watch = new Stopwatch(timer);

function start() {
  toggleBtn.textContent = 'Stop';
  watch.start();
}

function stop() {
  toggleBtn.textContent = 'Start';
  watch.stop();
}

toggleBtn.addEventListener('click', function() {
  watch.isOn ? stop() : start();
});

resetBtn.addEventListener('click', function() {
  watch.reset();
});

function alertSystem(){
  var timer = document.getElementById('timer')
  alert(timer);
}
<h1 id="timer">00 : 00 . 000</h1>

<div>
  <button class=button id="toggle">Start</button>
  <button class=button id="reset">Reset</button>
  <button onclick='alertSystem()'>get number</button>
</div>

	    	

有很多代码,但这主要是为了使计时器正常工作。最后一个名为alertSystem()的函数在底部,它是触发警报调用的函数。对我而言,警报显示为[object HTMLHeadingElement]undefined。当我有alert(timer);时出现前者,但是如果我拥有alert(timer.value);alert(timer.length);则得到后者。

有人知道我如何才能在警报中获取计时器的值吗?


1 个答案:

答案 0 :(得分:3)

要获取计时器的值,您应该执行以下操作:

document.querySelector('#timer').innerHTML

否则,document.getElementById返回一个完整元素作为js对象。