[英]OnChange function for JQuery not firing
我正在使用JQuery 1.8.16。 我在页面上有许多用户控件,并希望捕获对这些控件的修改(如果有的话)。 因此,我在这些用户控件所在的父页面中使用JQuery的Onchange事件。 这是我的JQuery代码
$('input[type=text], input[type=file], textarea, select').on("change", function () {
var ctrl = $(this).attr('id');
if (ctrl.indexOf("ddlLibrary") != -1) {
needSave = false;
unlock = true;
UnlockRequest(null);
}
if (ctrl != null && ctrl != "") {
if (ctrl.indexOf("GeneralInformationControl") != -1
|| ctrl.indexOf("PartDetailsControl") != -1
|| ctrl.indexOf("UserInformationControl") != -1
|| ctrl.indexOf("AttachmentControl") != -1) {
if (ctrl.indexOf("lbAttachments") != -1 || ctrl.indexOf("tbAttachmetnDesc") != -1 || ctrl.indexOf("FileUpload1") != -1) {
needSave = false;
window.onbeforeunload = routeUnlock;
unlock = true;
}
else {
needSave = true;
window.onbeforeunload = confirmExit;
unlock = true;
}
}
}
});
首先,我没有捕获页面上用户控件的任何文本框,下拉列表或TextArea所做的任何编辑。 其次,我在documen.ready函数中放置了与此类似的另一个方法,如下所示
//JQuery Function to Call Lock Method on Editing any of the User Controls on Request Page
var locked = false;
$("input,select,textarea").change(function () {
if (!locked) {
$.ajax({
type: "POST",
url: "WebForm1.aspx/methodInServer",
contentType: "application/json; charset=utf-8",
success: function (msg) {
locked = true;
alert(msg.d);
}
});
}
});
});
我在这些函数中设置了断点,但很惊讶没有一个断点被击中,而且我对用户控件中的字段所做的更改都没有被捕获。 关于为什么会发生任何积极的想法?
您不会显示任何页面源,也不会提及您的JavaScript是在单独的.js
文件中,还是在<script>
块中的页面中,以及是否出现在页面中(这很重要)。 我通常建议将页面,脚本和样式分开,并在页面源中适当地链接.js
和.css
文件。
正如我在评论中提到的那样,如果在构建DOM之前运行javascript,则处理程序可能无法附加到您要定位的控件上,因此这些控件尚不存在。 由于您使用的是jQuery,因此您想使用其.ready()
函数来等到DOM构建完成(“就绪”)之后再附加处理程序。
基本上[1],您只需将代码包装在一个匿名函数中,该函数在ready时被调用。
在页面头中,拉入脚本文件...
<!-- file: mypage.??? -->
<head>
<title>My Page</title>
<link rel="stylesheet" type="text/css" href="mystyles.css">
<script type="text/javascript" src="myscripts.js"></script>
</head>
脚本文件包含您的代码,并包装在准备就绪时调用的函数中。
// file: myscripts.js
$(document).ready(
function() {
// Your original code goes here...
$('input[type=text], input[type=file], textarea, select')
.on("change", function () {
var ctrl = $(this).attr('id');
if (ctrl.indexOf("ddlLibrary") != -1) {
needSave = false;
unlock = true;
UnlockRequest(null);
}
if (ctrl != null && ctrl != "") {
// etc.
}
// more of your code
});
} // end of anonymous "ready" function
);
[1]“基本上”-但要做的更多。 我不会在这里尝试完整的教程,因为关于SO的问题已经很多,围绕它的问题进行了讨论。
(免责声明)
type="text/javascript"
或type="text/css"
。 我提到这一点是为了避免页面和代码片段上的所有挑剔行为,但是人们还是觉得需要做些事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.