在页面打开时运行Javascript

Running Javascript as page opens

本文关键字:运行 Javascript      更新时间:2023-09-26

我有一个小问题,我想运行javascript一旦页面打开,但它不适合我。在许多论坛和教程,我尝试他们建议使用onload函数在我的情况下:

<body onload="loadPage()">  

所以我的脚本被称为loadPage,但它不工作…而不是打开其中一个页面(if, else if语句中的链接)-只是有一个空白页面。任何帮助,非常感谢!

<%@ include file="header.jsp" %> 
<%@ page import="java.sql.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ page import="java.util.ArrayList" language="java" %>
<%@ page import="java.text.MessageFormat" language="java" %>
<%@ page import="java.util.List" language="java" %>
<%@ page import="java.util.ArrayList" %>
<%
    String place = request.getParameter("place");
%>
<html>
<head>
<script type="text/javascript">
function loadPage() 
{
    if( <%=place%> == "birr")
    {
       window.open("http://localhost:82/IrishClimateData/Birr.jsp");
    }
    ...more else if statemens here...   
    else if( <%=place%> == "Shannonairport")
    {
       window.open("http://localhost:82/IrishClimateData/Shannon airport.jsp");
    }
}
</script>
</head>
<body onload="loadPage()">  
</body>
</html>

我尝试了不同的选项,并做了以下操作:

var placeName = "<%=place%>";
if( placeName == "birr")

我还必须加上;在函数的末尾。我以为apache tomcat会像往常一样把它指向我,但它没有…谢谢大家!

删除服务器端代码并简化loadPage函数后,它看起来会运行良好。下面是一个实例:http://jsbin.com/ozetah/2/?place=birr

活动示例代码:

<html>
<head>
<script type="text/javascript">
function loadPage() {
  // code to replicate server side capture of GET parameter
  var place = /place=(.*?)(?:$|&)/.exec(document.location.search);
  if( place.length >1 ) { place = place[1]; }

  if( place == "birr") {
    window.open("http://localhost:82/IrishClimateData/Birr.jsp");
  } else if( place == "Shannonairport") {
    window.open("http://localhost:82/IrishClimateData/Shannon airport.jsp");
  } else {
    alert('place param of "'+place+'" doesn''t match');
  }
}
</script>
</head>
<body onload="loadPage()">  
</body>
</html>

既然所有这些工作,你没有看到任何错误在你的代码,我会检查html输出,以确保你的服务器端代码输出你所期望的。您可以取出所有的服务器端代码,并开始添加片段,看看是什么破坏了它。