【发布时间】:2015-09-22 17:06:28
【问题描述】:
我需要取消嵌套以下代码,因为严格的 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>
【问题讨论】:
-
this引用未正确绑定,并且您将this作为参数传递,我建议首先将其更改为具体的变量名。您可以尝试var self = $(this);并将其传递给该函数,或使用bind(this)
标签: javascript jquery html strict