简体   繁体   English

在Spring MVC中,在加载了Ajax的元素的onChange事件上调用javascript函数

[英]Call javascript function on onChange event of an element loaded with Ajax in Spring MVC

I have a drop down list with two values (for now..) with other elements in a form. 我有一个下拉列表,其中包含两个值(目前为..)以及表单中的其他元素。 What I'd like to do is enable four components if the user selects the first value and disable them otherwise. 我想做的是,如果用户选择第一个值,则启用四个组件,否则禁用它们。

There's a main page, and the user navigates through other pages opening and closing tabs loaded dynamically with ajax calls, that remove the current page and load the new page into a specific div. 有一个主页,用户浏览其他页面,打开和关闭通过ajax调用动态加载的选项卡,这些选项卡删除当前页面并将新页面加载到特定的div中。

In those pages loaded with Ajax I need to put the javascripts that will be used in those pages, so in this case the javascript that enables/disables the desired components, but I cannot call it because I get " Uncaught ReferenceError: soggettiNaturaChangeEvent is not defined ", where soggettiNaturaChangeEvent is the name of the function. 在那些加载了Ajax的页面中,我需要放置将在这些页面中使用的javascript,因此在这种情况下,启用/禁用所需组件的javascript,但是由于我收到“ Uncaught ReferenceError:soggettiNaturaChangeEvent未定义 ,因此无法调用它”,其中soggettiNaturaChangeEvent是函数的名称。

Here's where I call it, in the page newEditSoggetti.jsp: 在newEditSoggetti.jsp页面中,这就是我称之为的地方:

<form:select id="soggetti_soggettiNatura" path="soggettiNatura" cssStyle="width:300px;"       onChange="javascript:soggettiNaturaChangeEvent();">
...
...
...

In that page too I put the javascript function: 我也在该页面中添加了javascript函数:

<script id="function1" type="text/javascript">
    alert("soggettiNaturaChangeEvent");
    function soggettiNaturaChangeEvent()
    {
        alert("function soggettiNaturaChangeEvent");
        var natura = document.getElementById('soggetti_soggettiNatura'); 
        var datanascita = document.getElementById('soggetti_soggettiDataNascita');
        var luogonascita = document.getElementById('soggetti_soggettiLuogoNascita');
        var sesso1 = document.getElementById('soggettiSessoID1');
        var sesso2 = document.getElementById('soggettiSessoID2');
        if(natura.value == "Persona fisica")
        {
        datanascita.disabled=false;
        luogonascita.disabled=false;
        sesso1.disabled=false;
        sesso2.disabled=false;
    }
    else
    {
        datanascita.disabled=true;
        luogonascita.disabled=true;
        sesso1.disabled=true;
        sesso2.disabled=true;
    }
}
</script>

Here's my tab refresh function, which calls an initScript specified in a parameter: 这是我的标签刷新功能,它调用在参数中指定的initScript:

//reset stuff, reorder tabs, etc...
$.ajax(action,
{
success : function(result)
{
    //finds the div where to put new content
var doc = document.getElementById(newid);
doc.innerHTML = doc.innerHTML + result;

    //finds the initScript "scriptId" and runs it (THIS WORKS)
scripts = $('#' + scriptId); 
eval(scripts.html());

    //here I try to find all the scripts tag that begin with "function" and eval them
    var jScripts = $("[id^=function]");
for(var i = 0; i < jScripts.size(); i++)
{
       eval(jScripts.html());
   jScripts = jScripts.next();
}
}
});

The page prints the first alert when (I think) it appends the function to the DOM, but when I click on the component that should invoke the function I get the error. 该页面在(我认为)将功能附加到DOM时会打印第一个警报,但是当我单击应调用该功​​能的组件时,会收到错误消息。 What I'd like to do is to have this function get executed when I click on the component soggettiNatura, not when ajax finished loading my page. 我想做的是让此功能在我单击组件soggettiNatura时执行,而不是在ajax完成加载页面时执行。 Thanks to everyone who will try to help me, and to everyone that has posted useful content I read in the past. 感谢所有试图帮助我的人,以及所有张贴了我过去阅读过的有用内容的人。 Keep with the great work. 继续努力。 Andrea PS: sorry for the bad indentation, I'm in a bit of a hurry :P Andrea PS:不好意思,我很着急:P

Edit: a little append: if I try to load the page normally (not with Ajax) the javascript works... I have a function in the main page that shows me the actual html code after the various javascripts and ajax modifications (this is purely to debug) and the javascript function I'm trying to call is there in the dom... Please help a newbie in this world.. 编辑:一点附加:如果我尝试正常加载页面(不使用Ajax),则javascript可以正常工作...我在主页上有一个函数,可以显示各种javascript和ajax修改后的实际html代码(这是纯粹是为了调试),而我尝试调用的javascript函数在dom中...请帮助这个世界的新手。

I finally made it. 我终于做到了。 I'm posting a sample web page with all the relevant code: 我要发布一个带有所有相关代码的示例网页:

<%@ page language="java" isELIgnored="false" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<jsp:directive.include file="/WEB-INF/sitemesh-decorators/include.jsp"/>
<fmt:setBundle basename="bundles.settori-resources"/>
<!-- !!!!! important for popup !!!!! I have a boolean param passed from the server to know if I'm opening in popup mode or in tab mode -->
<% Boolean isPopup = (Boolean)request.getAttribute("popup"); %>
<!-- !!!!! important for popup !!!!! -->

<div id="contentarea" >
<div id="lb"><div id="rb"><div id="bb"><div id="blc">
<div id="brc"><div id="tb"><div id="tlc"><div id="trc">
<div id="content">
    <h2><fmt:message key="navigation.management"/> <fmt:message key="settori.title"/></h2>
    <div id = "initScriptSettori"></div>
    <form:form id="tabSettoriForm" method="POST" commandName="settori">
        <!-- !!!!! important for popup !!!!! I'm saving the id of the element of the calling page I'm going to edit with the selected element in the popup -->
        <form:hidden path="hiddenCallerFormElementId" />
        <!-- !!!!! important for popup !!!!! -->
        <table cellpadding="0" cellspacing="0" id="viewTable">
            <tbody>
                <tr>
                    <td class="label" valign="top">
                        <fmt:message key="settori.settoreid.title"/>:
                    </td>
                    <td>
                        <form:input id="settori_settoreId" path="settoreId" cssStyle="width:300px;"/>
                    </td>
                    <td class="label" valign="top">
                        <fmt:message key="settori.settoredescrizione.title"/>:
                    </td>
                    <td>
                        <form:input id="settori_settoreDescrizione" path="settoreDescrizione" cssStyle="width:300px;"/>
                    </td>
                </tr>
            </tbody>
        </table>

        <!-- !!!!! important for popup !!!!! It triggers two different search functions based on the popup staying open or not: the first updates the popup with the search results, the second updates the tab -->
        <% if(isPopup == null || isPopup == false) {%>
            <span class="inputbutton"><input class="refreshbutton" type="button" id="searchSettori" onClick="javascript:refreshTabWithPost('tabSettori', 'tabSettori', '${pageContext.request.contextPath}/searchSettori', '<fmt:message key="navigation.management"/> <fmt:message key="settori.title"/>', 'initScriptSettori')" value="<fmt:message key="navigation.searchSettori"/>"/></span>
        <% } else {%>
            <span class="inputbutton"><input class="refreshbutton" type="button" id="searchSettoriPopup" onClick="javascript:postColorbox('/DeliDete/searchSettoriPopup', '', 'tabSettoriForm','initScriptSettori')" value="<fmt:message key="navigation.searchSettori"/>"/></span>
        <% } %>
        <!-- !!!!! important for popup !!!!! -->

    </form:form>

    <div class="clear">&nbsp;</div>
    <!-- !!!!! important for popup !!!!! If I'm on the tab version shows the new entity button, else it is hidden -->
    <% if(isPopup == null || isPopup == false) {%>      
        <div class="navitem"><a class="button" href="javascript:refreshTab('tabSettori', 'tabSettori', '${pageContext.request.contextPath}/newSettori', '<fmt:message key="navigation.new"/> <fmt:message key="settori.singular"/>', 'initScriptSettori')"><span><img src="${pageContext.request.contextPath}/images/icons/new.gif" /><fmt:message key="navigation.new"/> <fmt:message key="settori.singular"/></span></a></div>
    <% } %>
    <!-- !!!!! important for popup !!!!! -->

    <div id="tablewrapper">
    <table id="listTable" cellpadding="0" cellspacing="0">
        <thead>
            <tr>
                <th class="thead">&nbsp;</th>
                <th class="thead"><fmt:message key="settori.settoreid.title"/></th>
                <th class="thead"><fmt:message key="settori.settoredescrizione.title"/></th>
            </tr>
        </thead>
        <tbody>
            <c:forEach items="${settoris}" var="current" varStatus="i">
                <c:choose>
                    <c:when test="${(i.count) % 2 == 0}">
                        <c:set var="rowclass" value="rowtwo"/>
                    </c:when>
                    <c:otherwise>
                        <c:set var="rowclass" value="rowone"/>
                    </c:otherwise>
                </c:choose> 
            <tr class="${rowclass}">
                <td nowrap="nowrap" class="tabletd">

                    <!-- !!!!! important for popup !!!!! If I'm in the tab version of the page it shows the view,edit and delete buttons, if I'm in the popup version it shows the select button, which triggers the closing of the popup and the update of the calling element -->
                    <% if(isPopup == null || isPopup == false) {%>
                        <a title="<fmt:message key="navigation.view" />" href="javascript:refreshTab('tabSettori', 'tabSettori', '${pageContext.request.contextPath}/selectSettori?settoreIdKey=${current.settoreId}&', '<fmt:message key="navigation.view"/> <fmt:message key="settori.title"/>','initScriptSettori')"><img src="images/icons/view.gif" /></a>
                        <a title="<fmt:message key="navigation.edit" />" href="javascript:refreshTab('tabSettori', 'tabSettori', '${pageContext.request.contextPath}/editSettori?settoreIdKey=${current.settoreId}&', '<fmt:message key="navigation.edit"/> <fmt:message key="settori.title"/>', 'initScriptSettori')"><img src="images/icons/edit.gif" /></a>
                        <a title="<fmt:message key="navigation.delete" />" href="javascript:refreshTab('tabSettori', 'tabSettori', '${pageContext.request.contextPath}/confirmDeleteSettori?settoreIdKey=${current.settoreId}&', '<fmt:message key="navigation.delete"/> <fmt:message key="settori.title"/>','initScriptSettori')"><img src="images/icons/delete.gif" /></a>
                    <% } else {%>
                        <a title="<fmt:message key="navigation.select" />" href="javascript:closeColorbox('${current.settoreId}', '${current.settoreDescrizione}', '${settori.hiddenCallerFormElementId}')"><img src="images/icons/select.png" /></a>
                    <% } %>
                    <!-- !!!!! important for popup !!!!! -->
                </td>
                <td nowrap="nowrap" class="tabletd">

                        ${current.settoreId}
                    &nbsp;
                </td>
                <td nowrap="nowrap" class="tabletd">

                        ${current.settoreDescrizione}
                    &nbsp;
                </td>
            </tr>
            </c:forEach>
        </tbody>
    </table>
    </div>
</div>
</div></div></div></div>
</div></div></div></div>
</div>

<!-- !!!!! important for popup !!!!! -->
<script>
function initLoad()
{
//necessary for the popup init script loading
if(jQuery1_6_2("#initScriptSettori").length != 0)
{
    jQuery1_6_2.getScript("javascripts/pagesJs/" + "initScriptSettori" + ".js", function() 
    {
        window["initScriptSettori"]();
    });
}
else
    setTimeout("initLoad()",500);
}
initLoad();
</script>
<!-- !!!!! important for popup !!!!! -->

The initScriptSettori.js: initScriptSettori.js:

function initScriptSettori()
{
}

In this case I had nothing to initialize, but there are so many cases in which you need some javascripts events being fired at the end of the loading of the page, well I put them inside the function initScriptSettori. 在这种情况下,我没有什么要初始化的,但是在很多情况下,您需要在页面加载结束时触发一些javascripts事件,所以我将它们放在函数initScriptSettori中。

Hope this helps guys. 希望对大家有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM