简体   繁体   English

如何将两个相似的javascript函数结合在一起?

[英]How can I combine two similiar javascript functions?

Is there a way to combine the following two instructions into more efficient code? 有没有一种方法可以将以下两个指令组合成更有效的代码?

  $('.sandwiches').mouseleave(function () {
    $('.sandwiches').hide();
});
$('.food').mouseleave(function () {
    $('.sandwiches').hide();
});

通过组合选择器:

$('.sandwiches,.food').mouseleave...

Merge the selectors : 合并选择器

$('.sandwiches, .food').mouseleave(function () {
    $('.sandwiches').hide();
});

You could attach a defined function to each element: 您可以将定义的函数附加到每个元素:

function hideElement(e) {
    $(this).hide();
}

$('.sandwiches,.food').mouseleave(hideElement);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM