首页 > 解决方案 > 文件中包含的 JS 函数没有被调用?

问题描述

当我在下拉框中选择一个项目时,包含在 Struts 2 jsp 页面中的 Javascript 函数history.js不会被调用。

这是我在开发者工具中看到的错误

Uncaught ReferenceError: getClasses is not defined
    at HTMLSelectElement.onchange (history.action:279)

这是如何包含在 jsp 页面中的

<%@ taglib uri="/WEB-INF/struts-tags.tld" prefix="s"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<script type="text/javascript" src="<s:url value='/js/common/ajax.js'/>"/>
<script type="text/javascript" src="<s:url value='/js/common/sorttable.js'/>"/>
<script type="text/javascript" src="<s:url value='/js/common/CalendarPopup.js'/>"/>
<script type="text/javascript" src="<s:url value='/js/common/skuformatting.js'/>"/>
<script type="text/javascript" src="<s:url value='/js/common/formatsku.js'/>"/>
<script type="text/javascript" src="<s:url value='/js/history.js'/>"/>
<script type="text/javascript">
    var cal = new CalendarPopup();      
</script>
...
...
<td align="center"> 
    <s:select id="form.search.deptFilter"  property="form.search.deptFilter" 
     list="form.deptSelectList" onchange="getClasses()" size="5"
     listKey="name" listValue="value" headerKey="-1" headerValue="Select a Department" />
</td>
...

getClasses()在中定义history.js,这里是该文件中的方法定义。

...
    function getClasses(){
        var selectionComponent = document.getElementById('form.search.deptFilter');
        if(selectionComponent.options[selectionComponent.selectedIndex].value == -1)
            return;
        clearSubClasses();
        document.getElementById('form.search.classFilter').options.length = 0;  // Empty class select box
        sendAjaxRequest(selectionComponent,createClass);
    }
...

我在开发人员工具的源代码部分注意到的一件事是,我没有看到 js 文件夹中的 jsp 页面中包含的所有 js 文件,我认为这是问题所在,但不确定原因。但几周前,一切都很好。

知道为什么history.js文件中的 js 方法没有被调用吗?

标签: javascripthtmlstruts2struts

解决方案


问题是您的 JSP 页面生成了无效的 HTML。加载时它仍然调用它的元素的顺序。然而<script>,标签在一个单独的线程中由浏览器异步调用。

并且文件加载不会等待他们完成。Hense,你还没有定义对函数的引用,因为这个函数还没有加载。为了确保在文档中使用它之前定义一个函数,您应该使用文档就绪事件。

通常的做法是使用 和标签创建文档,<head>并将标签放在. 中定义的所有功能都可用于元素。<body><script><head><head><body>


推荐阅读