JavaScript(警告信息)

3
我已经编写了一个JavaScript警告消息代码,在1和2两个代码中,它首先显示警示信息再显示HTML内容。我该怎么做才能先运行HTML内容然后再运行JavaScript代码? 代码1:
<!DOCTYPE html>
<html>
    <head>
        <title>Hello, World !</title>

    </head>
    <body>
        <h1>I am learning JavaScript.</h1>
        <div id="Content">
            <p>This is a paragraph tag. Here the content of html.</p>
        </div>
        <script src="text.js"></script>
    </body>
</html>

代码 2

<!DOCTYPE html>
<html>
    <head>
        <title>Hello, World !</title>
    </head>
    <body>
        <h1>I am learning JavaScript.</h1>
        <div id="Content">
            <p>This is a paragraph tag. Here the content of html.</p>
        </div>
        <script>
alert(" This is alert message.");
</script>
    </body>
</html>

在这两个示例中,脚本在 HTML 内容之后运行。您应该能够在警告框后面的页面上看到标题。 - coagmano
这个回答解决了你的问题吗?在所有内容加载完毕后使用JS弹出警告框 - aerial
5个回答

3

有一个load事件,在页面加载之后将被触发。您可以监听该事件:

window.addEventListener('load', function() {
    console.log('All assets are loaded');
    alert ("This is an alert MSG");
})

0
你可以使用 setTimeout() 来实现这个功能。
<html>
    <head>
        <title>Hello, World !</title>
        </head>
        <body>

          <h1>I am learning JavaScript.</h1>

          <div id="Content">
             <p>This is a paragraph tag. Here the content of html.</p>
          </div>

        <script>
         setTimeout(()=>{
           alert(" This is alert message.")     
          },2000)

        </script>
      
      </body>
  
   </html>

不要等待2秒钟,然后弹出警报消息会让访问者感到惊讶。 - Raptor
哈哈哈!让我们把它缩短到1秒钟。 - MagnusEffect
这是一个不正确的解决方案。你无法保证所有页面元素在特定时间内都已加载完成。 - Raptor

0

尽量不要参考非官方的来源:w3schools。请参考 MDN。 - Raptor

0
你可以使用 window.onload 函数。这个函数在页面加载完成后调用。
<!DOCTYPE html>
<html>
    <head>
        <title>Hello, World !</title>
    </head>
    <body>
        <h1>I am learning JavaScript.</h1>
        <div id="Content">
            <p>This is a paragraph tag. Here the content of html.</p>
        </div>
        <script>
        window.onload = function () { 
            alert(" This is alert message.");
        }
        </script>
    </body>
</html>

-1

按照以下方式创建您的脚本

<script type = "text/javascript">  
            function displayalert() {  
  
  
               alert ("This is an alert MSG");  
            }  
      </script> 

将这段代码添加到你的 HTML 文档中(这是一个按钮)

<input type = "button" value = "Click me" onclick = "displayalert();" />  

当您点击此按钮时,您将看到警报。 我们使用onclick属性并调用displayalert()函数,在其中定义了alert()。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接