我必须在我们的CMS中使用一个模板,该模板预先加载了旧版本的jQuery Validate插件,并编写了我的代码以使用更新版本的jQuery Validate。如果这两个版本加载在同一页面上,它将无法验证,我无法/权限取消链接旧的jQuery Validate插件,我必须使用较新的jQuery Validate插件。
有没有办法解决这个问题?它有类似jQuery.noConflict()
的内容吗?
答案 0 :(得分:2)
您可以使用jquery中的noConflict函数创建一个hacky环境来隔离您的validate版本。但是,如果您需要同时插入旧版本和新版本的验证,则必须将其导入两次或自行复制这些函数。这里有一个片段来说明这一点:
<div class="container main">
<div class="row">
<div class="col-md-12">
<form name="old-val" id="old-val">
Age: <input type="text" name="age">
<br />
Postal: <input type="text" name="postal">
<br />
<input type="submit" value="Test">
</form>
<hr />
<form name="new-val" id="new-val">
Email: <input type="text" name="email">
<br />
Postal: <input type="text" name="postal">
<br />
<input type="submit" value="Test">
</form>
</div>
</div>
<hr>
<footer>
</footer>
</div>
<script src="js/vendor/jquery/jquery-2.1.3.js"></script>
<!-- These 3 scripts below only be available to $jqVal114 -->
<script src="js/vendor/bootstrap/js/bootstrap.js"></script>
<script src="js/vendor/bootstrap-dialog/bootstrap-dialog.js"></script>
<script src="js/vendor/block-ui/jquery.blockUI.js"></script>
<!-- This will put jQuery 2.1.3 in a place holder and replace the global $ with ver 1.3 -->
<script src="js/jquery13.js"></script>
<!-- These 2 scripts below only be available to $jqVal106 -->
<script src="js/jquery.validate106.js"></script>
<script src="js/vendor/jquery-form/jquery.form.js"></script>
<script>
// this will take the jQuery 2.1.3 in the place holder back into the global space ie $ == jquery2.1.3
$jqVal06 = jQuery.noConflict(true);
</script>
<script src="js/jquery.validate114.js"></script>
<script src="js/postalCodeCA.js"></script>
<script>
$jqVal14 = $;
</script>
<script>
(function($, jQuery){
// val v1.06
$("#old-val").submit(function(){
var $frm = $(this);
if ($frm.valid()){
alert('No errors from v1.6');
}
return false;
}).validate({
debug: true,
rules: {
age: {
required: true,
digits: true
}
}
});
}($jqVal06, $jqVal06));
(function($, jQuery){
// val v1.14
$("#new-val").submit(function(){
var $frm = $(this);
if ($frm.valid()){
alert('Valid Form, from v1.14');
}
return false;
}).validate({
debug: true,
rules: {
email: {
required: true,
email: true
},
postal: {
postalCodeCA: true
}
}
});
}($jqVal14, $jqVal14));
</script>
答案 1 :(得分:1)