'$(“#elementId”)。change()'无效,'$(文件).on(“更改”“elementId”)'工作正常

时间:2014-01-10 07:01:22

标签: javascript jquery dom onchange

最近,我的网页上发生的情况是,即使是已经存在的jsp页面元素,$("#elementId").change()也不起作用,$(document).on("change" "elementId"也可以。看起来页面document已经准备好了,因此页面元素上的直接事件处理程序不会被添加。有提示吗?

ps:我所谈论的元素并非动态生成。

JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/receipt.js"></script>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/myCss.css" >
<title>Generate Report</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
</head>

<body>
<form:form action="getReceipt.html" commandName="viewQuote">
<div class="main_div">
<div>
    <table>
        <tr><td valign="top" align="left">
                Res Number
            </td>
            <td  valign="top" align="left" >
                <input id="reservatnNo" type="text" name="reservatnNo" value="">
            </td>
            </tr>
        </table>
</div>

<div>
    <table>
        <tr><td>
                <button id="generateReportButton" type="submit">
                    Submit Form
                </button>
            </td>
        </tr>
    </table>
</div>

</div>
</form:form>
</body>

的Javascript

$( document ).ready(function() {
    jQuery.ajaxSettings.traditional = true;
});


$(document).on("change", "#reservatnNo", function(event) {
//$('#reservatnNo').change(function(){
    alert("changeddd");
});

1 个答案:

答案 0 :(得分:2)

确保$("#elementId").change()位于$(document).ready()函数内。

否则$(“#elementId”)返回空的jQuery对象(因为控件尚不存在)并且没有注册任何事件。

ready方法之外,可以使用$(document).on()或旧方法$(document).bind()来实现可靠的事件处理。