You do not need to "inject" the script that way. In fact, this can create problems if the selector picks up more than one element in the frame by duplicating the listeners.
//código html a ser injetado na página
var codigo = '<div id="teste"><input type="submit" id="botao" value="Send" /></div>';
//insere o elemento no local adequado
$('#iframe5').parent().after(codigo);
//adicione um handler no botão adicionado pelo ID
$("#botao").click(function() { alert("test"); });
I've put a working example on jsfiddle .
It is also possible to retrieve a jQuery type reference for the created elements and then add the listener to the button:
//transforma código html a ser injetado na página em elementos reais com o jQuery
var codigo = $('<div id="teste"><input type="submit" id="botao" value="Send" /></div>');
//localiza o botão a adiciona o listener
codigo.find('input').click(function() { alert("test"); });
//insere o elemento no local adequado
$('#iframe5').parent().after(codigo);
The advantage of this is that you do not need to set id
.
Another approach is to use the on
function of jQuery so you do not have to associate the event with the button just created. Example:
$(document).on("click", "#botao", function() { alert("test"); });
Running the above code only once at page startup will work for any element with id botao
created at any time.
Note : Be careful not to create multiple elements with the same id
. This is not good practice and can lead to problems.