我想使用 jQuery
查看三个文本框是否已更改,以便我可以通过 AJAX
发送数据。
我尝试了一个简单的脚本:
$("#name, #position, #salary").change(function()
{
console.log("All data are changed");
});
其中name、position、salary是三个文本框各自的ID。
结果是,当我更改第一个时:
当我改变第二个时:
这是第三个:
因此,当每个文本框分别更改时,我收到了消息。我需要做的是当这三个改变时,显示消息。我是 jQuery 的新手,所以我想知道我是否可以在 jQuery 中使用类似 IF ... AND ... AND
的东西。
最佳答案
一旦用户更改了值,许多验证框架都有脏输入的概念。您可以实现它并检查您的所有字段何时变脏。
$("#name, #position, #salary").change(function() {
this.classList.add("dirty");
if ($(".dirty").length === 3) {
console.log("All data are changed");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="position" />
<input id="salary" />
我们可以将其抽象为一个 jQuery 插件以实现可重用性
$.fn.allChange = function(callback) {
var $elements = this;
$elements.change(function() {
this.classList.add("dirty");
if (callback && $elements.filter(".dirty").length === $elements.length) {
callback.call($elements);
}
});
return $elements;
}
$("#name, #position, #salary").allChange(function() {
console.log("All data are changed");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="position" />
<input id="salary" />
关于javascript - 我们可以使用 and 运算符来组合多个 jQuery 事件吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35146168/