函数连接:在一个函数中以逗号分隔

function concat comma separated in one single function

本文关键字:函数 分隔 一个 连接      更新时间:2023-09-26

我有这样一个场景:

$(".table1 table tbody tr").hover(
    function() {
        $(this).css('background-color', 'red');
    },
    function() {
        $(this).css("background-color", "");
    }
);
$(".table2 table tbody tr").hover(
    function() {
        $(this).css('background-color', 'red');
    },
    function() {
        $(this).css("background-color", "");
    }
);
为了避免重复添加删除两个函数的css,我想将公共部分隔离成一个函数。我试过了,但我想我有一些关闭问题。
$(".table1 table tbody tr").hover(
    self.setColor(this)
);
$(".table2 table tbody tr").hover(
    self.setColor(this)
);
self.setColor = function(context) {
    return (
        function() {
            $(context).css('background-color', 'antiquewhite');
        },
        function() {
            $(context).css("background-color", "");
        }
    );
};

你想错了。

function onHover(event) {
  $(this).css('background-color', 'red');
}
function onLeave(event) {
  $(this).css('background-color', '');
}
$(".table1 table tbody tr").hover(onHover, onLeave);

您仍然需要传递两个参数,所以创建两个函数并分别传递它们

我建议使用一个通用的css类,而不是试图简化函数:

<script> 
     $(".my-table table tbody tr").hover(function() {
            $(this).css('background-color', 'red');
        },
        function() {
            $(this).css("background-color", "");
        });
</script>
当然,你甚至可以通过一个简单的css样式来实现(我不确定你是否故意避免使用css):
<style>
 .my-table table tbody tr:hover{
   background-color:red; 
}
</style>