jquery :: Why does hover trigger instantly?

后端 未结 2 1595
臣服心动
臣服心动 2020-12-21 19:18

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



        
2条回答
  •  心在旅途
    2020-12-21 19:41

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

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

    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);
    
    sup

提交回复
热议问题