You don’t 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 doubling 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 put a working example on jsfiddle.
It is also possible to retrieve a jQuery 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 don’t need to pin a id
.
Another approach is to use the function on
jQuery to not need to associate the event to the newly created button. Example:
$(document).on("click", "#botao", function() { alert("test"); });
Running the above code once at page startup will work for any element with id botao
created at any time.
Note: take care not to create multiple elements with one id
. This is not good practice and can lead to problems.
If you have using some CMS, it may prevent you to insert script tags directly on the page.
– Fábio Rocha