每次单击都会将其功能的性能提高到一

each click increases the performance of its functions to one

本文关键字:性能 功能 单击      更新时间:2023-09-26

每次函数再次运行时单击按钮。为什么?

我必须点击两次,但我不会只点击一次。

在谷歌chrome中试试这个代码。

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>
        <div id="one" > &nbsp Srboljub Petrovic</div>
        <input type="button" id="f" value="Klikni" onclick="f1();"></input>
        <script>
        function f1()
        {
            $("#f").click(function()
            {
                $("#one").slideUp();
                $("#one").css("border", "5px solid gray");
                $("#one").css("background-color", "red");
                $("#one").css("color","white");
                $("#one").slideDown();
            });
        }
        </script>
    </body>
</html>

您在点击处理程序中绑定了一个点击处理程序,因此每次单击按钮时,都会绑定一个新的点击事件处理程序,并且它会不断增加。

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script type="text/javascript">
          $(function() {
            $("#f").on('click', function() {
               $("#one").slideUp(function() {
                  $(this).css({border         : "5px solid gray",
                               backgroundColor: "red",
                               color          : "white"})
                         .slideDown();
               });
            });
          });
        </script>
    </head>
    <body>
        <div id="one">&nbsp Srboljub Petrovic</div>
        <input type="button" id="f" value="Klikni" />
    </body>
</html>

请注意,输入元素没有结束标记,jQuery方法是可链接的
此外,要在元素向下滑动后向上滑动,请使用回调。

之所以会发生这种情况,是因为您在HTML中分配了单击处理程序,然后每次调用它时都在f1中再次分配另一个处理程序。如果您使用Javascript分配事件处理程序,则不应该在HTML:中也分配它们

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  </head>
  <body>
    <div id="one" > &nbsp Srboljub Petrovic</div>
    <input type="button" id="f" value="Klikni"></input>
    <script>
      $("#f").click(function(){
        $("#one").slideUp();
        $("#one").css("border", "5px solid gray");
        $("#one").css("background-color", "red");
        $("#one").css("color","white");
        $("#one").slideDown();
      });
    </script>
  </body>
</html>

在绑定点击函数之前,请确保解除绑定。

function f1()
{
    $("#f").unbind("click").click(function()
    {
        //code
    });
}