【问题标题】:function is getting called repeatedly in JQuery函数在 JQuery 中被重复调用
【发布时间】:2013-11-23 00:43:58
【问题描述】:

默认情况下,我希望任何具有“.options”类的按钮执行与警报(“Hello World”)相同的操作。如果您往下看,您会看到另一个按钮,其 id 名称为“append_another_content”。它的工作是附加另一个<input type="button" class=".options" value="Option"> 并使其执行与其余“.options”按钮相同的操作。但是,除非我再次调用 myFunction(),否则刚刚添加的按钮不会执行任何操作,现在的问题是,一旦我再次调用 myFunction(),一旦添加了新内容,之前的按钮就会带有类 '.options'将根据您按下“附加”按钮的次数重复调用 myFunction()。我的目标是,每次单击“.options”按钮时只调用一次 myFunction()。

<html>
    <head></head>
    <body>
        <div id="wrap">
            <input type="button" class=".options" value="Option">
            <input type="button" class=".options" value="Option">
            <input type="button" class=".options" value="Option">
            <input type="button" class=".options" value="Option">
        </div>

        <input type="button" id="append_another_content" value="Append"/>
    </body>

    <script>
        function myFunction(){
            $('.options').click(function(){
               alert('Hello Friends!');
            });
        }

        //By default I want any buttons with a class '.options' to perform the same actions which is to alert('Hello World')
        myFunction();

        $('#append_another_content').click(function(){
            $.ajax({
                type: 'POST',
                url: 'ajax/get_another_button.php',
            }).done(function(data){
                $('#wrap').append(data);
                //The data will just return '<input type="button" class=".options" value="Option">'

                //The button that has just been appended will not perform any action unless I call myFunction()
                myFunction();
            });

        }); 


    </script>
</html>

【问题讨论】:

    标签: javascript jquery function func


    【解决方案1】:

    这是因为新元素没有绑定的处理程序,只有现有的处理程序(在调用 myFunction 之前 DOM 上的处理程序)。再次调用 myFunction 会添加另一个处理程序,依此类推。

    考虑改用委托,现有祖先持有现有和未来后代的处理程序。离祖宗越近越好。这样一来,您就只调用一次myFunction

    In this example,祖先#wrap 持有.options 的处理程序。这将对所有现有和未来的.options 生效。

    HTML:

    <div id="wrap">
        <input type="button" class="options" value="Option">
        <input type="button" class="options" value="Option">
        <input type="button" class="options" value="Option">
        <input type="button" class="options" value="Option">
    </div>
    <input type="button" id="append_another_content" value="Append" />
    

    JS:

    $('#wrap').on('click', '.options', function () {
      alert('Hello Friends!');
    });
    
    $('#append_another_content').click(function () {
      $(this)
        .siblings('#wrap')
        .append('<input type="button" class="options" value="Option">');
    });
    

    【讨论】:

    • 不,我得到了相同的结果。一旦我点击了“追加”按钮。当您开始单击具有类名“选项”的上一个按钮时,它们会开始向同一功能发出两次警报。
    • @ILikebanana 我放了一个带有答案的演示。
    • 我忘了添加,但是如果附加的数据来自ajax返回怎么办。我在上面编辑了我的问题。
    【解决方案2】:

    首先,去掉 HTML class 属性中的 .。就目前而言,$(".options") 没有选择任何内容,因为没有带有class="options" 的元素。应该是

    <input type="button" class="options" value="Option" />
    

    接下来,在创建按钮时将点击处理程序添加到按钮:

    $(/*...*/).appendTo($(this).siblings("#wrap")).click(handler);
    

    或使用委托:

    $("#wrap").on("click", ".options", handler);
    

    【讨论】:

      【解决方案3】:

      当您将事件处理程序添加到新创建的元素时,您还会向所有先前的元素添加另一个事件处理程序。

      您可以仅将事件处理程序添加到您创建的元素:

      function myFunction(e){
          $(e).click(function(){
             alert('Hello Friends!');
          });
      }
      
      myFunction('.options');
      
      $('#append_another_content').click(function(){
          var input = $('<input type="button" class=".options" value="Option">');
          $(this).siblings('#wrap').append(input);
          myFunction(input);
      });
      

      编辑:

      使用来自 AJAX 调用的数据,您可以做同样的事情:

      var input = $(data);
      $('#wrap').append(input);
      myFunction(input);
      

      【讨论】:

      • 我忘了添加,但是如果附加的数据来自ajax返回怎么办。我在上面编辑了我的问题。
      • @ILikebanana:你可以这样做。我在上面添加了一个示例。
      • 不,你不能这样做,因为 $.ajax({}).done(function(){//Can't reach myFunction})
      • @ILikebanana:你的函数是全局的,可以从代码中的任何地方访问。
      • 你是对的,但是一旦添加了新内容,该功能仍然会被多次触发。最后一个内容工作得很好,它只触发了一次功能。但其余的“.options”不止一次触发了 myFunction。
      猜你喜欢
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多