我需要取消嵌套以下代码,因为严格的javascript在Safari和Firefox中抛出错误(出于某种原因,它在Chrome中有效),该函数只能在顶层或在另一个函数中声明,而$不是功能。所以我认为我需要拆分函数声明。该代码应该以必需的形式循环遍历所有元素,如果未使用所有必需的字段,则阻止提交。
其他说明:我正在使用Google Apps脚本进行开发,该脚本需要严格的JavaScript。还要注意,“#submitbutton”实际上是一个常规按钮,它会调用google.script处理提交。
原始代码:
<script type="text/javascript">
$('#submitbutton').on('click', function() {
$(this).val("Submitting...");
//check for required fields
var emptyFields = $('[required]').filter(function() {
$(this).removeClass("warning");
if ($(this).val().length === 0){
$(this).addClass("warning")
return true
} else {
return false
}
});
if (emptyFields.length === 0) {
$(this).prop('disabled', true);
document.getElementById('incompleteWarning').style.display = 'none';
document.getElementById('bePatient').style.display = 'inline';
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(this.parentNode);
} else{
$(this).val("Submit Application")
document.getElementById('incompleteWarning').style.display = 'inline';
document.getElementById('incompleteWarning').style.color = 'red';
}
});
</script>
我尝试将其分解为下面的代码,但现在它甚至无法在Chrome中运行。我做错什么了吗?
<script type="text/javscript">
$('#submitbutton').on('click', validatefunction('#submitbutton'));
function validatefunction(this) {
$(this).val("Submitting...");
//check for required fields
var emptyFields = $('[required]').filter(filterfunction(index));
if (emptyFields.length === 0) {
$(this).prop('disabled', true);
document.getElementById('incompleteWarning').style.display = 'none';
document.getElementById('bePatient').style.display = 'inline';
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(this.parentNode);
} else{
$(this).val("Submit Application");
document.getElementById('incompleteWarning').style.display = 'inline';
document.getElementById('incompleteWarning').style.color = 'red';
}
};
function filterfunction(this){
$(this).removeClass("warning");
if ($(this).val().length === 0){
$(this).addClass("warning");
return true;
} else {
return false;
}
};
</script>
最佳答案
jQuery将使用先前期望的上下文来调用您的函数。这意味着您只需要执行以下操作:
$('[required]').filter(filterfunction);
和
$('#submitbutton').on('click', validatefunction);