problems when creating dynamically Event listeners

Asked

Viewed 49 times

2

http://jsfiddle.net/njszasq7/

JQUERY/Javascript

verificaCamposRepetidos(".teste", array1);
verificaCamposRepetidos(".teste1", array2);

HTML:

<p id="parte1">
    <span>VALORES de 1 a 3</span><BR/>
    <input type="text" class="teste"><BR/>
    <input type="text" class="teste"><BR/>
    <input type="text" class="teste"><BR/>
</p>
<p id="parte2">
    <span>VALORES de 1 a 5</span><BR/>
    <input type="text" class="teste1"><BR/>
    <input type="text" class="teste1"><BR/>
    <input type="text" class="teste1"><BR/>
    <input type="text" class="teste1"><BR/>
    <input type="text" class="teste1"><BR/>
</p>

the problem is occurring when I will type in the block (#parte1), he’s talking to type in numbers 1 à 5 and not of 1 à 3, looks like it only does the validation of the last Function that was added.... (verificaCamposRepetidos(".teste1", array2);)

2 answers

1


Your problem is happening due to variable totalPerguntas that is getting the value of the last call of the function verificaCamposRepetidos(); To solve this, simply move the variable assignment down to the .on() as below:

$(element).on("change", function () {
        valorAtual = $(this).val();
        totalPerguntas = $(element).length;
        //Resto da lógica
});

Follows the jsfiddle updated.

0

Yesterday afternoon I got the idea to stop writing so much the same js code. And that’s when I discovered something wonderful to use ( complicates a little at first to understand, but then it goes) ...

<div> Menu
<ul>
    <li data-method="abreTela"> Menu 1</li>
    <li data-method="abreTela2"> Menu 2</li>
    <li data-method="abreTela3"> Menu 3</li>
</ul>

With this HTML, in other times I would have something similar to this in my js to assign the events.

var tela = document; //ou outra logica para definir a tela e context atual..
tela.querySelectorAll('ul li')[0].addEventLis ....
tela.querySelectorAll('ul li')[1].addEventLis ....
tela.querySelectorAll('ul li')[2].addEventLis ....

// ou algo semelhante a isso recuperando por id, ou class, ou afins ...

However, when added an eventListener to the parent object div, by clicking on the child objects, the event is also fired ...

Therefore, just implement the logic to define the execution according to what was clicked. Follow an example demonstrating ..

Added the eventListener in the parent object, and in the Menu.actions function, it performs the treatment.

http://jsfiddle.net/statelessbr/deLLybho/

  • 1

    $("div"). on("click", "li", Function(){ }); Does the same thing. Events are propagated from the target element to their parents until they reach Document. Thus: $(Document). on("click", "div ul li", Function(){ }); It would also work. or Document.addeventlistener(click, Function(){ });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.