on ('click') running more than once

2

When I click on an area and then on the button .more1 for the first time correctly performs the function but if I click on one area after another and click on the button .more1 it executes the function twice, the function executes the number of times I click on the element.

I could not identify the error, has anyone had this problem? Does anyone know the solution?

 $("area").click(function(){         

    var escrever = '';
    var a = $(this).attr('class');
    var x = $.inArray(a,paises1);
    var clicado = x;

    t = ataques_possiveis[x].length;
    meus_territorios_tamanho = meus_territorios.length;

    if(opcao==2){

        for(w=0; w<meus_territorios_tamanho; w++){
            if(meus_territorios[w]==x){
                $(".selecione").html(paises2[x]);
            }
        }

        $('body').on('click','.distribuir .mais1',function(){

            if($('.selecione').text()!='Selecione'){
                var local = $(this).parent().parent().children('h2').text().replace(':','');
                var ter = $.inArray($(".selecione").text(),paises2);
                var pos_local = $.inArray(local,nomes_locais);

                for(var z=0; z<meus_territorios_tamanho; z++){
                    if(local==nomes_locais[0]){//verifica o tipo de exercito
                        if((meus_territorios[z]==x)&&(distribuir_locais[pos_local]>0)){
                            distribuir_locais[pos_local] = distribuir_locais[pos_local] -1;
                            exercitos[ter] = exercitos[ter]+1;
                            $('.'+ter).text(exercitos[ter]);
                            $(this).parent().parent().children('.dist_local').text(distribuir_locais[pos_local]);
                        }
                    }
                }
            }                                 
        });
    }
});
    
asked by anonymous 18.09.2015 / 14:46

1 answer

3

In fact it will occur every time the click event area element is clicked. It may be that .mais1 is inside it, so it may seem like the click of it is doing, but not necessarily.

What you can do is to take the creation of the click event from .mais1 from within the area click, since you are assigning the event to body itself. If the .mais1 pends on area depends on the opcao and the if (which appears to be global) to be equal to two, you can replicate the condition in .off() within the event:

$('body').on('click','.distribuir .mais1',function() 
{
    if(opcao == 2 && $('.selecione').text()!='Selecione')

Another solution is to use .mais1 , but I do not recommend it because it would be a gambiarra, but it would be useful if the rule were "click area should only work after a click on %code% . p>

$('body').off('click','.distribuir .mais1').on('click','.distribuir .mais1')
    
18.09.2015 / 14:51