JQuery事件在动态内容中重复

时间:2012-05-05 19:41:35

标签: javascript jquery

在我正在制作的网站页面中,按下按钮会导入另一个php页面的内容并将其附加到页面上。但是,其他页面包含JQuery,并且每次导入内容时,click事件($(“。ExpandRoleButton”)。click)都会在之前的元素上重复。所以,如果我添加3个元素;

元素1:重复点击事件3次

元素2:重复点击事件2次

元素3:运行一次点击事件

$("#AjouterPiece").click(function() 
{
    $.blockUI({ message: '<img src="images/ChargementGeant.gif"/><br/><h1>Un moment svp.</h1>' });
    $.post("wizardincl/piste.php", {newPiste: newPiste}, function(data)
    {
        $("#wizardPistes").append(data);
        $.unblockUI();
        $(".divNewPiste").fadeTo(300, 1);
        $("#nbExemplaires").attr("max", newPiste);
        newPiste++

        $( ".ExpandRoleButton").click(function()
        {
            if ($(this).hasClass('RetractRoleButton'))
            {
                $(this).find('img').attr('src', 'images/ExpandPetitNoir.png');
                var that = $(this);
                $(this).parent().parent().parent().parent().next().slideUp(500, function() {
                    that.parent().parent().parent().parent().css('border-bottom', '1px solid #FF790B');
                });
                $(this).removeClass('RetractRoleButton');
            }
            else
            {
                $(this).parent().parent().parent().parent().css('border-bottom', 'none');
                $(this).find('img').attr('src', 'images/ExpandPetitNoirRetour.png');
                $(this).parent().parent().parent().parent().next().slideDown(500);
                $(this).addClass('RetractRoleButton');
            }
        });

    });
});

目前,部分JQuery网站似乎失败了,经过一些搜索,我找不到任何解决问题的方法。有没有办法让代码不再像这样重复?

3 个答案:

答案 0 :(得分:4)

您可以使用.click(function(e) {...})传递事件,然后调用e.stopImmediatePropagation()仅触发当前处理程序,但这只会解决症状,而不是真正的问题。

编辑:确保您只是通过向选择器添加上下文来绑定新按钮的实例,例如$('.ExpandRoleButton', data)。由于您在一个类上匹配,该选择器将获取页面上的所有按钮;上下文允许您只选择结果中的一个。

答案 1 :(得分:4)

这是因为您将事件绑定到多个事件处理程序。第一次点击#AjouterPiece时,所有.ExpandRoleButton按钮都会绑定到onclick处理程序。

下次点击#AjouterPiece时,它会再次绑定。

为了防止这种情况,您必须在绑定之前使用以下代码unbind点击处理程序

$( ".ExpandRoleButton").unbind('click')

答案 2 :(得分:0)

一个好的做法(仅用于防止发生此类问题,添加意外的多点击处理程序)是...

$(".selector").off('click').on('click', function...

$(".selector").unbind('click')...
$(".selector").bind('click')...