我對jQuery有效函數有問題。在IE上時,它不起作用,有效始終返回true。我用這個代碼:client side validation with dynamically added field如何使jQuery有效函數在IE上可靠地工作?
以下是圖表:
Chrome IE
jquery-1.6.1 works not working
jquery-1.4.4 works works
1.6無法在IE工作了。不過,1.4.4 jQuery對IE有效。
這裏的
的jsfiddle友好
測試(測試這個本地HTML):
<!--
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<form id="XXX">
<input type="submit" id="Save" value="Save">
</form>
<script type="text/javascript">
// sourced from https://stackoverflow.com/questions/5965470/client-side-validation-with-dynamically-added-field
// which I do think don't have a bug
(function ($) {
$.validator.unobtrusive.parseDynamicContent = function (selector) {
//use the normal unobstrusive.parse method
$.validator.unobtrusive.parse(selector);
//get the relevant form
var form = $(selector).first().closest('form');
//get the collections of unobstrusive validators, and jquery validators
//and compare the two
var unobtrusiveValidation = form.data('unobtrusiveValidation');
var validator = form.validate();
$.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
if (validator.settings.rules[elname] == undefined) {
var args = {};
$.extend(args, elrules);
args.messages = unobtrusiveValidation.options.messages[elname];
$('[name=' + elname + ']').rules("add", args);
} else {
$.each(elrules, function (rulename, data) {
if (validator.settings.rules[elname][rulename] == undefined) {
var args = {};
args[rulename] = data;
args.messages = unobtrusiveValidation.options.messages[elname][rulename];
$('[name=' + elname + ']').rules("add", args);
}
});
}
});
}
})($);
// ...sourced from others
// my code starts here...
$(function() {
var html = "<input data-val='true' " +
"data-val-required='This field is required' " + "name='inputFieldName' id='inputFieldId' type='text'/>";
$("form").append(html);
var scope = $('#XXX');
$.validator.unobtrusive.parseDynamicContent(scope);
$('#Save').click(function (e) {
e.preventDefault();
alert(scope.valid());
});
});
// ...my code ends here
</script>
UPDATE
我想我上的jsfiddle代碼,它有副作用,jQuery的1.6有效的是在IE上工作。不要在jsFiddle上測試這段代碼。在您的本地html上測試此代碼
您使用的是什麼版本的IE? – reporter 2011-05-26 07:31:23
我最近使用了你在那裏找到的動態解析函數,我似乎無法複製這個問題,似乎所有的工作都在1.6.1和IE上。也許這與你添加一個帶有驗證的自定義輸入的方式有關。你可以在JSFiddle上運行起來嗎? – Henry 2011-05-26 08:51:33
這是很多代碼。有些甚至不包括HTML/JS。如果您最小化代碼量,您更有可能獲得答案。 – 2011-05-26 11:28:18