jquery / javascript:从iframe中的表单捕获提交事件?

时间:2013-06-21 04:19:23

标签: javascript jquery

假设我有一个带有iframe的网页,其中包含一个表单。我想在提交表单时在隐藏字段中设置一个值。提交表单时如何在主页面中触发事件?

这是我正在尝试做的简化版本:

  <!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>

1 个答案:

答案 0 :(得分:8)

试试这个,

$('#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
  });
});

摘自How can i bind an event to an element inside a local iframe?

可能是Selecting a form which is in an iframe using jQuery

的副本