JQuery事件在动态内容中重复 [英] JQuery Event repeating in dynamic content

查看:141
本文介绍了JQuery事件在动态内容中重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In a page of a website I'm making, the press of a button imports the contents of a another php page and appends it onto the page. However, that other page contains JQuery, and the click event($( ".ExpandRoleButton").click) repeats itself on previous elements every time I import the content. So if I add 3 elements;

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

Element 1: Repeats the click event 3 times

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

Element 2: Repeats the click event 2 times

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

Element 3: Runs the click event once

$("#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网站的一部分似乎已关闭,经过一些搜索后,我找不到任何内容解决这个问题。有没有办法让代码不再像这样重复?

Currently, part of the JQuery website seems down and after some search, I can't find anything to solve the problem. Is there any way to keep the code from repeating itself like this?

推荐答案

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

This is because you are binding the event to multiple event handlers. The first time #AjouterPiece is clicked, all .ExpandRoleButton buttons get binded to an onclick handler.

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

The next time #AjouterPiece is clicked, it gets binded again.

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

To prevent this, you must unbind the click handlers using the following code before binding it

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

这篇关于JQuery事件在动态内容中重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆