jQuery 在 iframe 中获取父值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18051748/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:26:32  来源:igfitidea点击:

Getting parent value in an iframe?

javascriptjqueryhtml

提问by user1016403

I have below two html files. In PassValueIFrame.htmli have an iframe which refers inputForm.html. Also, i have one hidden field in PassValueIFrame.htmland am trying to retrieve its value in inputForm.htmlbut am not getting its value it alerts as 'undefined'. Am i doing any wrong here? Please help me.

我有以下两个 html 文件。在PassValueIFrame.html我有一个 iframe,它指的是inputForm.html. 另外,我有一个隐藏字段PassValueIFrame.html,我试图检索它的值,inputForm.html但没有得到它的值,它警告为“ undefined”。我在这里做错了吗?请帮我。

PassValueIFrame.html

传递值IFrame.html

<html>
  <head>
  <title>IFrame Example</title>
  </head>
<body>
<input type="hidden" class="Language" value="English">
<iframe name="iframe" id="iframe_id" src="inputForm.html" height="150" >
</iframe>
</body>
</html>

inputForm.html

输入表单.html

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script language="javascript">
  $(document).ready(function() {
    alert($(this).parent().find('.Language').html());
  });

  </script>
   <title>IFrame Child Example</title>
</head>
<body>
<h1> Iframeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee </h1>
</body>

Thanks!

谢谢!

回答by Abhitalks

<input id="myInput" type="hidden" class="Language" value="English">

$("#myInput", window.parent.document).val();

回答by Alex

Try this:

尝试这个:

alert(parent.document.getElementsByClassName("Language")[0].value);

or add id (for example languageId) to the hidden element and try

或将 id (例如languageId)添加到隐藏元素并尝试

alert(parent.document.getElementById("languageId").value);

回答by Nabil Kadimi

Another thing you can do is define a function in the parent window and call it from the iframe:

您可以做的另一件事是在父窗口中定义一个函数并从 iframe 调用它:

inputForm.html

输入表单.html

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script language="javascript">
        $(document).ready(function() {
            window.parent.parent_function("Papa!");
        });
    </script>
    <title>IFrame Child Example</title>
</head>
<body>
    <h1> Iframeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee </h1>
</body>
</html>

PassValueIFrame.html

传递值IFrame.html

<html>
    <head>
    <title>IFrame Example</title>
    <script>
        function parent_function(str) {
            window.alert(str);
        }
    </script>
</head>
<body>
    <input type="hidden" class="Language" value="English">
    <iframe name="iframe" id="iframe_id" src="inputForm.html" height="150" >
    </iframe>
</body>
</html>