jquery :: Why does hover trigger instantly?

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

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



        
相关标签:
2条回答
  • 2020-12-21 19:28

    Because you are invoking the function by adding () at the end, what you can do is to pass a anonymous function as the mouseenter callback which can call showSelector with the desired arguments like

    function showSelector(position) {
      alert(position);
    }
    
    function hideSelector() {}
    
    $("#1").hover(function() {
      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>

    0 讨论(0)
  • 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);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="" id="1">sup</a>

    0 讨论(0)
提交回复
热议问题