Why do not jquery events work when I create an object via javascript innerHTML?

2

I am making the following code:

var botoesTela = "<button id='okcad' class='botao_padrao botao_ok' value='OK' onclick=''> <img src='/php/Images/OK.png' alt='OK' /> OK </button>";
divBotoes.innerHTML = divBotoes.innerHTML + botoesTela;

But when I try to get the click button on the HTML page

$("#okcad").click(function() 

It does nothing ... does anyone know why?

    
asked by anonymous 27.11.2014 / 03:01

1 answer

3

Two reasons (errors in the code) that can lead to this problem:

# 1

Problem: The element is created after of this jQuery to be read.
Solution: You need to delegate the event. New code: $(document).on('click', "#okcad", function(){

# 2

Problem: Duplicate IDs if you are eventually adding buttons like this several times. Solution: Classes instead of IDs or generate IDs dynamically to be unique.
New code: $(".botao_padrao.botao_ok").click(function(){

You can combine the two ideas and use: $(document).on('click', '.botao_ok', function(){

    
27.11.2014 / 07:11