How to enable onclick after a jquery? [duplicate]

1

I have botões that are mounted dynamically via jquery , it happens that on the main page I have events of these botões , but since they do not exist yet at the time of loading the page the events are not loaded, I needed do something like a refresh on these events as soon as jquery was loaded.

Code:

Abre Pagina HTML
$(".meusbtns").click(function...);
Monta HTML Basico
Clica numa lista e essa lista traz o result por um jquery
<button class="meusbtns" value="x">Botao</button>

Note that the class meusbtns exits, but since it came with jquery the event was not initially loaded.

I know there is a way to add and remove classes, which would reset the event, but since these buttons are dynamic I can not figure out how to do that.

I hope I have been clear

    
asked by anonymous 04.11.2016 / 14:44

2 answers

4

Here's another question on the same subject:

How to ensure that an element will have the DOM event?

Use outside the pageLoad:

$(document).on("click", ".meusbtns", function(){
    /*Seu Código*/
});

The .on("click"): function can work dynamically with elements that have been created later on the page.

    
04.11.2016 / 15:02
0

Simple, you have to bind these click events after mounting the buttons.

Example:

function montaView() {
  ... // supondo que você tenha montado seus botoes
  bindEventos();
}

function bindEventos() {
  ... // faz o bind dos eventos
}

Attention!

If you call the bind event on an element that already has its binds, it will bind again and the event will run x times that you have binded. To avoid this you can use .off() to remove the previously bound event and redo the bind.

Example:

botoesNaoDinamicos.off('click');
todosOsBotoes.click(...);
    
04.11.2016 / 14:55