jquery ::为什么要立即悬停触发? [英] jquery :: Why does hover trigger instantly?

查看:87
本文介绍了jquery ::为什么要立即悬停触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在加载页面后会立即触发悬停事件?

Why does the hover event trigger as soon as the page is loaded?

function showSelector(position) {
  alert(position);
}
	
function hideSelector() {
}

$("#1").hover(showSelector(17), hideSelector);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="" id="1">sup</a>

推荐答案

因为你正在调用函数而不是引用它。

Because you're calling the function instead of referencing it.

$("#1").hover(showSelector(17), hideSelector);
//                        ^^^^

使用 showSelector(17) 作为回调 hover 函数将首先调用该函数,然后将其返回值分配给悬停回调。要解决此问题,您可以使用匿名函数作为回调,然后使用参数调用其中的函数。

Using showSelector(17) as callback to the hover function will call the function first and then assign it's return value to the hover callback. To solve the issue, you can use anonymous function as callback and then call the function inside it with parameters.

function showSelector(position) {
  alert(position);
}

function hideSelector() {}

$("#1").hover(function() {
  // Use anonymous function
  // Call the function with parameter here
  showSelector(17);
}, hideSelector);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="" id="1">sup</a>

这篇关于jquery ::为什么要立即悬停触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆