简体   繁体   English

jQuery:按钮单击多次触发

[英]jQuery: Button click triggers multiple times

On my site I have multiple buttons and every button is loaded on the site twice through ajax from the same file. 在我的网站上,我有多个按钮,并且每个按钮通过ajax从同一文件两次加载到网站上。

Though my problem is that this event fires twice if the same button is loaded twice. 虽然我的问题是,如果同一按钮被加载两次,则此事件将触发两次。 Though it works fine if only one of the buttons is loaded. 如果只加载一个按钮,则效果很好。

My code: 我的代码:

index.php 的index.php

<div id="firstButtonContainer">
</div>

<div id="secondButtonContainer">
</div>

<script>

    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js";
    script.onload = function(){

        $.ajax({
            url: '/test/firstButtonContainer.php',
            success: function(msg) {
                jQuery('#firstButtonContainer').html(msg);
            }
        });

        $.ajax({
            url: '/test/secondButtonContainer.php',
            success: function(msg) {
                jQuery('#secondButtonContainer').html(msg);
            }
        });

    };document.body.appendChild(script);

</script>

buttons.php Buttons.php

<button class="testbutton">Button1</button>
<button class="testbutton">Button2</button>
<button class="testbutton">Button3</button>
<button class="testbutton">Button4</button>

<script>

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js";
script.onload = function(){



$(".testbutton").on("click", function(event){
  alert("this should only appear once");
});


};document.body.appendChild(script);

</script>

firstButtonContainer.php firstButtonContainer.php

<div id="buttons">
</div>

<script>
$.ajax({
    url: '/test/buttons.php',
    success: function(msg) {
        jQuery('#buttons').html(msg);
    }
});
</script>

secondButtonContainer.php secondButtonContainer.php

<div id="buttonsTwo">
</div>

<script>
$.ajax({
    url: '/test/buttons.php',
    success: function(msg) {
        jQuery('#buttonsTwo').html(msg);
    }
});
</script>

Try 尝试

$(".testbutton").on("click", function(event){
  event.preventDefault();
  alert("this should only appear once");
});

OR 要么

$(".testbutton").on("click", function(event){
  event.stopPropagation();
  alert("this should only appear once");
});

event.stopPropagation() event.stopPropagation()

Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. 说明:防止事件使DOM树冒泡,从而防止任何父处理程序收到该事件的通知。

event.preventDefault() event.preventDefault()

Description: If this method is called, the default action of the event will not be triggered. 说明:如果调用此方法,则不会触发事件的默认操作。

Comment Response 评论回应

index.php 的index.php

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

    $(function()
    {
        $.ajax({
            url: 'test/firstButtonContainer.php',
            success: function(msg) {
                jQuery('#firstButtonContainer').html(msg);
            }
        });

        $.ajax({
            url: 'test/secondButtonContainer.php',
            success: function(msg) {
                jQuery('#secondButtonContainer').html(msg);
            }
        });

        $(".testbutton").live("click", function(event)
        {
            event.preventDefault();
            alert("this should only appear once");
        });
    });

</script>

<div id="firstButtonContainer">
</div>

<div id="secondButtonContainer">
</div>

buttons.php Buttons.php

<button class="testbutton">Button1</button>
<button class="testbutton">Button2</button>
<button class="testbutton">Button3</button>
<button class="testbutton">Button4</button>

Your buttons are not firing the ajax calls properly, they should all have unique id's (ie testbutton1, testbutton2, etc...) and really be having onclick triggers in jQuery like so: 您的按钮无法正确触发ajax调用,它们都应具有唯一的ID(即testbutton1,testbutton2等),并且实际上在jQuery中具有onclick触发器,如下所示:

$("#testbutton1").click(function(){
  // do ajax call here for button1           
});

Your code is a bit odd to me! 您的代码对我来说有点奇怪! That happens because every time you fetch HTML through AJAX call you bind new event handler to all buttons because of css class selector you use. 发生这种情况是因为每次使用AJAX调用获取HTML时,都会由于使用的CSS类选择器而将新事件处理程序绑定到所有按钮。 To resolve this problem I have two suggestions: 要解决此问题,我有两个建议:

1- use a bit more complecated PHP code to generate a random ( or some pattern ) ID for each button and just use that unique IDs to bind new event. 1-使用更复杂的PHP代码为每个按钮生成随机(或某种模式)ID,并仅使用该唯一ID绑定新事件。

<?php
$id = "btn_id_" . rand (100,1000);
?>
<buttom class='whatever' id='<?php echo $id; ?>'>

$("#<?php echo $id; ?>").on("click", function(event){
  alert("this should only appear once");
});

2- IF you do not like above solution just use jQuery live trigger out side your AJAX requets: 2-如果您不喜欢上述解决方案,只需在AJAX记录之外使用jQuery实时触发:

a. 一种。 remove your onload script from buttons.php 从button.php删除您的onload脚本

b. b。 add the following javascript code to your index.php 将以下javascript代码添加到index.php

<script>
(".testbutton").live ( 'click', function () {
   alert ( "This happens only once!" );
});
</script>

And every thing should be fine. 每件事都应该没事。 jQuery live event takes care of every newly added element that selector and attaches event handler to it and gurantees that happens only once. jQuery live event负责选择器的每个新添加的元素,并将事件处理程序附加到该元素,并保证仅发生一次。

My personal choose is item no. 我个人的选择是项目编号。 1 1个

One reason is that you bind the same event more than once, each bind count, 原因之一是您多次绑定同一事件,每个绑定计数,
so, if this is the reason, you can solve it in this way: 因此,如果这是原因,您可以通过以下方式解决它:

// unbind the same event, before you bind it,
$("xxx").unbind("click").bind("click", function() {
    // ...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM