javascript中的警报未显示

alert in javascript not showing

本文关键字:显示 javascript      更新时间:2023-09-26
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
    if (document.getElementById("popup")) {
        window.alert("hi");
    }
    </script>
</head>
<body>
    <h1 id="popup">dfdfs</h1>
</body>
</html>

我有一个简单的javascript,它在h1id退出时显示警报,但我没有得到警报消息。jquery中的代码也可以提供帮助。

<script>标记放在body:的末尾

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <h1 id="popup">dfdfs</h1>
    <script type="text/javascript">
    if (document.getElementById("popup")) {
        window.alert("hi");
    }
    </script>
</body>
</html>

在元素之后编写script,使其在元素出现后运行。查看代码:

<!DOCTYPE html>
<html>
<body>
    <h1 id="popup">dfdfs</h1>
    <script type="text/javascript">
    if (document.getElementById("popup")) {
        window.alert("hi");
    }
    </script>
</body>
</html>

Plunkr表示:"http://plnkr.co/edit/0fznytLHtKNuZNqFjd5G?p=preview">

因为在document完全加载之前执行script,所以找不到元素#popup

  1. 使用DOMContentLoaded

使用DOMContentLoaded检查DOM是否已完全加载。

<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
    console.log("DOM fully loaded and parsed");
    if (document.getElementById("popup")) {
        window.alert("hi");
    }
});
</script>
  1. 使用jQuery ready

使用jQuery,可以使用ready方法检查DOM是否准备好。

$(document).ready(function() {
    if ($("#popup").length) {
        window.alert("hi");
    }
});
  1. script移动到body的末尾

您可以将script移动到body

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <h1 id="popup">dfdfs</h1>
    // Move it here
    <script type="text/javascript">
    if (document.getElementById("popup")) {
        window.alert("hi");
    }
    </script>
</body>
</html>

您的脚本位于要检索的h1元素之上。因此,它是在元素实际存在之前运行的。

将脚本移动到页面底部,或者将其包装在jQuery就绪块中。并考虑将其移动到外部文件中。

$(function() {
    if(document.getElementById("popup")) {
      window.alert("hi");
    }
});
   try this easy way. no need of jquery. 
    <html>
    <head>
    </head>
    <body>
 <h1 id="popup">dfdfs</h1>
    <script type="text/javascript">
    if(document.getElementById("popup")) {
      window.alert("hi");
    }
    </script>
 </body>
    </html>

<body>中使用<script>标记是一种很好的做法,因为它通过更快地加载来提高性能。

然后使用

<body>
<script>
    $(function() {
        if(document.getElementById("popup")) {
          window.alert("hi");
        }
    });
</script>
</body>

下面的代码为您提供解决方案

$(document).ready(function() {
    if (document.getElementById("popup")) {
        window.alert("hi");
    }
});