赢得't输入javascript if/else语句

Won't enter javascript if/else statement

本文关键字:if else 语句 javascript 输入 赢得      更新时间:2023-09-26

这里有一个简单的html页面,带有javascript。我无法让我的网页输入if语句中的任何一个。我可以在JSFiddle上使用它,但不能在我出色的文本编辑器的页面上使用。

<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>
  <body>
    resize this panel
    <p id="xy">
    </p>
    <script>
      $(document).ready(function() {
        // Execute on load
        checkWidth();
        // Bind event listener
        $(window).resize(checkWidth);
      });
      function checkWidth() {
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();
        $("#xy").text("width: "+windowWidth + "   height: " + windowHeight);
        if (windowWidth >= 700 && windowWidth <= 800 && windowHeight >= 400 && windowHeight <= 500) {
          alert("dimention matched");
        }
        else {
          alert("Nope")
        }
      }
    </script>
  </body>
</html>

您缺少jQuery库。将以下脚本放在</head> 之前

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>

当前代码到达此行时停止,因为美元符号是对jQuery的调用,而您没有它:$("#xy").text("width:"+windowWidth+"height:"+windowsHeight);

首先,我建议您包含jquery.min.js,您可以在jquery.com上下载。

接下来,更改JavaScript的顺序,在将要使用的函数用作快捷命令NameOfFunction()之前,应初始化该函数。

当您添加jquery时,就像同事们已经提到的那样,您仍然会遇到一个小问题:每次尝试调整窗口大小时,即使只有1px,也会遇到一条警报(甚至多条警报)。所以即使是测试以下内容也不那么烦人:

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <title></title>
</head>
<body>
  resize this panel
  <p id="xy">
  </p>
  <p id="another">
  </p>
  <script>
 function checkWidth() {
   var windowWidth = $(window).width();
   var windowHeight = $(window).height();
   $("#xy").text("width: "+windowWidth + "   height: " + windowHeight);
   if (windowWidth >= 700 && windowWidth <= 800 && windowHeight >= 400 && windowHeight <= 500) {
     $("#another").text("Match!");
   }
   $(window).resize(checkWidth);
 }  
$(document).ready(function() {
   // Execute on load
   checkWidth();
   // Bind event listener
   $(window).resize(checkWidth);
});
    </script>
</body></html>