How to attach an event to a button in an iframe
Right now I have a jQuery UI dialog with an <iframe>
inside of the dialog. When the user pushes a button, the dialog pops up with a form-editing screen in the iframe.
Well, I want to have two buttons in the inner form-editing screen, "cancel" and "ok". Can开发者_如何学JAVAcel doesn't save changes and closes the dialog, ok saves changes and closes the dialog. Pretty simple..
So how do I attach an event to the cancel button inside of the iframe from the parent page? I would also assume that you would somehow need to attach an event to the iframe's DOM-ready or else the button would not yet exist.
How do you do this?
Also, the iframe is on the same-domain and such so there is no cross-domain worries
A simple example is here at jsbin with the iframe source
Ok so here is what I did to accomplish this. I added this code to the iframe page:
$(document).ready(
function()
{
$("#cancelbutton").click(
function()
{
parent.CloseDialog();
});
});
Then in the opening page I put this:
function CloseDialog()
{
$('#diag').dialog('close');
}
So rather than try to close the dialog from the frame I just call a method in the parent page that will take care of closing it. Same effect but a lot easier. Couldn't seem to get the frame to let me use the dialog method. But this worked.
Does this get you close?
DialogBox.html:
<body>
<input type="submit" value="Edit" id="editbutton" />
<div id="diag">
<iframe src="/" ></iframe>
</div>
<script>
$(document).ready(function(){
$('#diag').dialog({
height: 100,
width: 100,
autoOpen: false
});
$('#editbutton').click(function(){
$('#diag iframe').attr('src','modal.html');
$('#diag').dialog('open');
});
$("#diag iframe").load(function() {
$("#diag iframe").contents().find('#cancelbutton').click(function() {
//close dialog here
});
});
});
</script>
</body>
onclick="parent.window.close();"
精彩评论