我使用 jQuery each
函数在悬停时调用鼠标事件:
$('.entry .post-entry a').each(function(){
root.setDimensions(this);
$(this).on("mouseenter", root.mouseEnter);
$(this).on("mousemove", root.mouseMove);
$(this).on("mouseleave", root.mouseLeave);
$(this).on("click", root.onClick);
});
这很好用,但我需要将项目的索引发送到这些函数。问题是,当我在每个函数末尾添加函数标记: ()
时,该函数将在页面加载后被调用,但我不希望这样。
我知道一种使用参数将变量发送到函数的方法。但要使用它们,您应该使用大括号,如下所示:
$('.entry .post-entry a').each(function(index){
var index = index;
root.setDimensions(this);
$(this).on("mouseenter", root.mouseEnter(index));
$(this).on("mousemove", root.mouseMove(index));
$(this).on("mouseleave", root.mouseLeave(index));
$(this).on("click", root.onClick(index));
});
如何在不直接调用函数的情况下发送值?
最佳答案
尝试使用bind()
:
$('.entry .post-entry a').each(function(index){
var index = index;
root.setDimensions(this);
$(this).on("mouseenter", root.mouseEnter.bind(this, index));
$(this).on("mousemove", root.mouseMove.bind(this, index));
$(this).on("mouseleave", root.mouseLeave.bind(this, index));
$(this).on("click", root.onClick.bind(this, index));
});
使用bind()
,您可以绑定(bind)(duh)函数的作用域(第一个参数),然后绑定(bind)执行时它将接收的参数(第二个和前向参数)。
事实上,@RoryMcCrossan 说的是真的:在循环中绑定(bind)事件并不好。最佳做法是将它们与一个选择绑定(bind)。 但是,他建议在事件内部使用index()
,这是否是一个好主意,取决于这些事件被调用的频率。为此,您可以混合使用两种方法,同时使用 bind()
和 index()
,但不要重复它们:
$.fn.onWithIndex = function(eventType, callback) {
$(this).on(eventType, function(e) {
var $el = $(this),
index = $el.data("index") ? $el.data("index") : $el.index();
$el.data("index", index);
callback.call(this, index, e);
});
};
// Use
$(".posts a").onWithIndex("mouseenter", root.mouseEnter);
此函数是如何执行此操作的示例。如果您经常需要此类事件,这可能是一个不错的选择。它运行一个事件包装器,在其中检查元素数据中的保存索引,如果未找到,则运行 index()
。请记住,此函数只是一个示例,不能像原始 on()
那样使用选择器参数,例如: $('...').on("mouseenter", "another-selector", function() { .. });
- 这是行不通的。
关于javascript - 如何使用每个函数内的函数发送值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38641664/