【问题标题】:jquery/javascript: Capture submit event from form in iframe?jquery/javascript:从 iframe 中的表单捕获提交事件?
【发布时间】:2013-06-21 04:19:22
【问题描述】:

假设我有一个带有 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>

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    试试这个,

    $('#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 可能重复

    【讨论】:

    • 这对我不起作用,输入字段没有得到更新。我已将 iframe 内容移动到单独的文件中,我在示例中显示的方式不正确,因此内部正文标签现在包含:
      fileuploaded :
    • 我猜这个解决方案的问题在于 $("input[name='fileuploaded']").val() = "1";是在 iframed 文档而不是父文档的上下文中执行的吗?
    • 您的解决方案效果很好,谢谢!问题是我在伪代码中引入的 val 分配问题,您在解决方案中进行了更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 2013-08-29
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    相关资源
    最近更新 更多