两个div切换,将多个javascript单击钩子合并为一个

时间:2017-05-30 06:11:18

标签: javascript jquery html

现在我有以下内容:

<script>
    $('#nav-close').on('click', function(){

      var mover = $('#mover');

      // register is not visible
      if(mover.css('opacity') === '1'){
        mover.css({'opacity': '0'});
      } else {
        mover.css({'opacity': '1'});
      }

    });
    $('#nav-expander').on('click', function(){

      var mover = $('#mover');

      // register is not visible
      if(mover.css('opacity') === '1'){
        mover.css({'opacity': '0'});
      } else {
        mover.css({'opacity': '1'});
      }

    });
</script>

如何将这两者合并为一个逻辑,如下所示,以获得更高效的脚本:

    $('#nav-close' || '#nav-expander').on('click', function(){

...

2 个答案:

答案 0 :(得分:2)

使用,代替||。请参阅jquery multiple selector documentation

$('#nav-close,#nav-expander').on('click', function() {
  var mover = $('#mover');
  // register is not visible
  if (mover.css('opacity') === '1') {
    mover.css({
      'opacity': '0'
    });
  } else {
    mover.css({
      'opacity': '1'
    });
  }

});

答案 1 :(得分:0)

    Please see:-
    Multiple Selector at => http://api.jquery.com/multiple-selector/
    Note, the double quotes around your div selectors. ;)

$("#nav-close, #nav-expander").click('click', function() {
var mover = $('#mover');
// register is not visible
if (mover.css('opacity') === '1') {
    mover.css({
    'opacity': '0'
});
} else {
    mover.css({
    'opacity': '1'
});
}

});