[英]How to query multiple conditions or results of anonymous functions in jQuery
First of all, I have a form with several input fields and some Bootstrap-Buttons. 首先,我有一个包含多个输入字段和一些Bootstrap-Button的表单。 Now, what I want to do is to check, if two conditions ("Are all input fields filled?" ; "Is at least one Button pushed down?") are fullfilled to enable the user to click the submit button. 现在,我要检查的是是否满足两个条件(“是否已填写所有输入字段?”,“是否按下了至少一个按钮?”)以使用户能够单击“提交”按钮。
This is my code: 这是我的代码:
function checkInput() {
var inputFields = $("input[name=inp1],[name=inp2],[name=inp3]");
var buttons = $("button[name=btn1],[name=btn2],[name=btn3]");
var empty1;
var empty2;
buttons.click(function() {
if(!$(this).hasClass('active')) {
empty1 = false;
} else {
empty1 = true;
}
});
inputFields.keyup(function() {
inputFields.each(function() {
if($(this).val().length == 0) {
empty2 = true;
} else {
empty2 = false;
}
});
});
alert(empty1);
alert(empty2);
if(empty1 == true && empty2 == true) {
$('button[name=submitBtn]').prop('disabled', false);
} else {
$('button[name=submitBtn]').prop('disabled', true);
}
}
The alert(...)
functions say, that empty1
and empty2
are "undifined", which i can understand. alert(...)
函数说, empty1
和empty2
是“未定义的”,我可以理解。 But my question is, how can I retrieve the true
or false
values from buttons.click()
and inputFields.keyup()
to query them afterwards? 但是我的问题是,如何从buttons.click()
和inputFields.keyup()
检索true
值或false
值以在以后查询它们?
The problem is the scope of the variables, those vars need to be global: 问题在于变量的范围,这些变量需要是全局的:
var empty1;
var empty2;
function checkInput() {
var inputFields = $("input[name=inp1],[name=inp2],[name=inp3]");
var buttons = $("button[name=btn1],[name=btn2],[name=btn3]");
buttons.click(function () {
if (!$(this).hasClass('active')) {
empty1 = false;
} else {
empty1 = true;
}
});
inputFields.keyup(function () {
inputFields.each(function () {
if ($(this).val().length == 0) {
empty2 = true;
} else {
empty2 = false;
}
});
});
alert(empty1);
alert(empty2);
if (empty1 == true && empty2 == true) {
$('button[name=submitBtn]').prop('disabled', false);
} else {
$('button[name=submitBtn]').prop('disabled', true);
}
}
Move it outside of the function an it will works: see it in jsFiddle working example 将其移出函数即可:在jsFiddle工作示例中查看
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.