如何在jQuery中将两个事件处理程序合并为一个? [英] How to combine two event handlers into one in jQuery?
本文介绍了如何在jQuery中将两个事件处理程序合并为一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种简单的方法将这两个jQuery函数组合为一个,从而消除了不必要的重复?
Is there a simple way to combine these two jQuery functions into one, thereby removing the unnecessary duplication?
$('form#search input').on('keyup', function() {
if ($(this).val() == '') {
$('a#clear').hide();
}
else {
$('a#clear').show();
}
});
$('form#search select').on('change', function() {
if ($(this).val() == '') {
$('a#clear').hide();
}
else {
$('a#clear').show();
}
});
感谢您的帮助.
推荐答案
如果您想以最优雅,最短的方式有条件地绑定它们,则可以执行以下操作:
If you want to bind these conditionally in the most elegant, shortest way possible you can do this:
var $formSearch = $('form#search'),
hideShow = function () {
if ($(this).val() == '') {
$('a#clear').hide();
}
else {
$('a#clear').show();
}
};
$formSearch.find('input').on('keyup', hideShow);
$formSearch.find('select').on('change', hideShow);
如果您希望两个选择器都触发这两个事件,则可以执行此操作.这样做可能是可以的,因为您可能希望无论如何都要触发它们.
If you want both event to be triggered for both selectors, you can do this. It might be okay to do this, since you might want these to be triggered anyways.
$('form#search input, form#search select').on('keyup change', function() {
if ($(this).val() == '') {
$('a#clear').hide();
}
else {
$('a#clear').show();
}
});
这篇关于如何在jQuery中将两个事件处理程序合并为一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文