为什么我不能在.on中调用我的函数?

时间:2015-12-30 05:11:00

标签: javascript jquery

我试图在使用之前将函数定义为变量,显然我可以使用 $(this).off('mouseleave',fadeOutt)将其关闭并 $(this).on('mouseleave',fadeOutt)将其重新打开。

为什么这样做:

<div class="table_bg">
<table datatable="ng" dt-options="dtOptions" dt-column-defs="dtColumnDefs" class="table table-striped table-bordered dt-responsive nowrap res_table" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>#</th>
            <th>Description</th>
            <th>Ali</th>
            <th> Extension</th>
            <th> Ext/th>
            <th>Comp</th>
        </tr>
    </thead>
    <tbody ng-hide="loading">
        <tr ng-class="{'selected':$index == selectedRow}" ng-click="setClickedRow($index)" ng-repeat="docType in DocTypes" ng-cloak ng-mouseenter="hover(docType)" ng-mouseleave="hover(docType)">
            <td>{{$index}}</td>
            <td>

                {{docType.Desc}}
            </td>
            <td>{{docType.LI}}</td>
            <td>{{docType.Ext}}</td>
            <td>{{docType.EXT}}</td>
            <td>{{docType.Comp}}</td>
        </tr>
    </tbody>
</table>

但不是这样:

    var fadeDarl = function(){         
$("#darl").on({ 
    mouseenter: function(){
        $("#bgimg1").stop(true,true).fadeIn(200);
},
    mouseleave: function() {
        $("#bgimg1").stop(true,true).fadeOut(200);
}
});
};

fadeDarl();

7 个答案:

答案 0 :(得分:2)

在此代码中:

 var fadeDarl = function(){         
$("#darl").on({ 
    mouseenter: fadeInn(),
    mouseleave: fadeOutt()
});
};

当您在fadeInn之后加上括号时,您调用该函数并将其返回值分配给mouseenter

您真正想要做的是将函数本身分配给mouseenter,以便稍后在指定的事件触发时调用该函数。
所以只需删除这些括号,它就会按预期工作。

如果您来自一种无法通过引用传递函数的语言,但在JavaScript函数中first-class objects,这可能会让您感到困惑。

答案 1 :(得分:1)

你需要传递函数而不是调用它:

更改

$("#darl").on({ 
    mouseenter: fadeInn(),
    mouseleave: fadeOutt()
});

$("#darl").on({ 
    mouseenter: fadeInn,
    mouseleave: fadeOutt
});

答案 2 :(得分:1)

删除括号。您正在调用该函数并返回该值,而不是将该函数分配给该事件。

mouseenter: fadeInn(),
mouseleave: fadeOutt()

答案 3 :(得分:1)

你传递的评价/结果不是函数本身,它应该是:

$("#darl").on({ 
    mouseenter: fadeInn,
    mouseleave: fadeOutt
});

答案 4 :(得分:1)

谁说你不能将fadeInn()更改为fadeInn

答案 5 :(得分:1)

当您执行mouseenter: fadeInn()时,您将使用fadeIn()的返回值绑定mouseenter事件。
因此,该函数只在绑定时被调用一次,然后在mouseenter上它将尝试调用返回值,即undefined。
因此,不应该绑定返回值,而应该

mouseenter: fadeInn

将完成工作

答案 6 :(得分:0)

老实说,你应该使用正确的工具来做正确的工作。这是css为之构建的东西。另外,你将获得由GPU而不是cpu加速的动画硬件,你不会锁定js的单个线程。唯一一次我喜欢js对css的限制是当我需要挂钩动画生命周期中的事件时,或者需要像补间一样更复杂的动画。

&#13;
&#13;
#darl figure {
  opacity: 0;
  visibility: hidden;
  transition: .2s all;
  display: inline-block;
}

#darl:hover figure {
  opacity: 1;
  visibility: visible;
}
&#13;
<div id="darl">
  <p>I am a div. there are many like me but this one is me</p>
  <figure id="bgimg1" class="fade_wrapper">
    <img src="http://lorempixel.com/100/100" />
    <figcaption>lorem pixel yall</figcaption>
  </figure>
</div>
&#13;
&#13;
&#13;

相关问题