jquery/javascript:从 iframe 中的表单捕获提交事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17227641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery/javascript: Capture submit event from form in iframe?
提问by AidanCurran
Lets say I have a web page with an iframe which contains a form. I want to set a value in a hidden field when the form has been submitted. How can I trigger an event in the main page when the form is submitted?
假设我有一个包含表单的 iframe 的网页。我想在提交表单后在隐藏字段中设置一个值。提交表单时如何在主页面上触发事件?
This is a simplified version of what I'm trying to do:
这是我正在尝试做的简化版本:
<!DOCTYPE html>
<html>
<head>
<title>TEST IFRAME UPLOAD</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
// Pseudo code for what I want to do
// (this of course doesn't work because target is inside iframe:
jQuery(document).ready(function() {
$("#file_upload_form").submit(function() {
$("input[name='fileuploaded']").val(1);
return true;
});
});
</script>
</head>
<body>
<form id="mainform" action="processform" method="post">
<input type="hidden" name="fileuploaded" value="">
<!-- more form fields here -->
</form>
<iframe id="upload-iframe">
<form enctype="multipart/form-data" id="file_upload_form" action="processfileupload" method="post">
Select an image to upload:<br/>
<input type="file" name="file">
<input type="submit" name="submit" class="submit" value="Upload">
</form>
</iframe>
</body>
</html>
回答by Rohan Kumar
Try this,
试试这个,
$('#upload-iframe').load(function() {
$(this).contents().find('#file_upload_form').submit(function() {
$("input[name='fileuploaded']").val("some value"); // updated
return true; //return false prevents submit
});
});
Refered from How can i bind an event to an element inside a local iframe?
Can be possible duplicate of Selecting a form which is in an iframe using jQuery