How to combine two event handlers into one in jQuery?

核能气质少年 提交于 2021-02-16 13:23:26

问题


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();
  }
});

Thanks for any help.


回答1:


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();
  }
});



回答2:


Define one function to handle the event and then assign it as follows:

function inputChanged() {
    if ($(this).val() == '') {
        $('a#clear').hide();
    }
    else {
        $('a#clear').show();
    }
}

$('form#search input').on('keyup', inputChanged);
$('form#search select').on('change', inputChanged);


来源:https://stackoverflow.com/questions/25494133/how-to-combine-two-event-handlers-into-one-in-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!