将alert()更改为getElementByID()

时间:2016-03-02 21:15:02

标签: javascript

如何使用window.alert()替换document.getElementByID().innerhtml以使用更现代的上述方法提醒消息输出?

这是我到目前为止所做的。

我的HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Alert Box Replacement</title>
    <script src="example.js"></script>
  </head>
  <body>
    <h1>JavaScript</h1>
    <h2>Javascript basics</h2>
  </body>
</html>

我的JS:

var response = confirm('Proceed to Checkout?');
var message;
if (response ==true) {
    message ="Checkout";
} else {
    message ="Continue Shopping";
}
alert(message);

谢谢!

1 个答案:

答案 0 :(得分:0)

根据innerHTML语句的结果替换HTML元素的confirm,就像这样简单:

if (confirm('Proceed to Checkout?')) {
   document.getElementById('message').innerHTML = "Checkout";
} else {
   document.getElementById('message').innerHTML = "Continue Shopping";
}
<h1>JavaScript</h1>
<h2>Javascript basics</h2>
<div id="message"></div>

(另见this Fiddle