javascript - 从 iframe 访问父页面的 id 元素

标签 javascript jquery html css iframe

如何从 iframe 访问 id 元素到父页面?我已经尝试使用此方法,但仍然无效。

Parent.html

<html>
    <head>
        <title>Parent</title>
    </head>
    <body> 
    <button id="click" onclick="alert('Hello');">click</button>
        <iframe id="iframe1" src="iframe.html">
        </iframe>
    </body>
</html>

iframe.html

<!DOCTYPE html>
<html>
    <head>
        <title>Parent</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-3.1.0.slim.js"></script>
<script>
$(function() {
    var money = 20000;

    $("#nominal").on("change keyup", function() {
        var input = $(this);

        // remove possible existing message
        if( input.next().is("form") )
            input.next().remove();

        // show message
        if( input.val() > money )
            window.parent.$('#click').trigger('click');
    });
});
</script>
    </head>
    <body> 
    <input type="text" id="nominal">
    </body>
</html>

我创建的脚本是否有问题?请帮助我改进这段代码。提前致谢。

问题已解决

最佳答案

尽管未在该上下文中定义,但您正试图在父窗口上使用 jQuery。它仅在子文档中定义。

改为更改您的子 iframe 脚本以在父窗口的元素上调用 jQuery。这是一个例子:

父文档

<html>
  <head>
    <title>Parent</title>
  </head>
  <body>
    <button id="click" onclick="alert('Hello')">click</button>
    <iframe id="iframe1" src="iframe.html">
    </iframe>
  </body>
</html>

子 (iframe) 文档

<!DOCTYPE html>
<html>
  <head>
    <title>Parent</title>
    <script type="text/javascript" src="//code.jquery.com/jquery-3.1.0.slim.js"></script>
  </head>
  <body> 
    <input type="text" id="nominal">

    <script>
      $(function() {
          var money = 20000;

          $("#nominal").on("change keyup", function() {
              var input = $(this);

              // remove possible existing message
              if (input.next().is("form")) {
                  input.next().remove();
              }

              // show message
              if (input.val() > money) {
                $(window.parent.document.getElementById('click')).trigger('click');
              }
          });
      });
    </script>
  </body>
</html>

https://plnkr.co/edit/ks8oFmQyxHYFt0h8eBbF?p=preview

或者

你也可以完全放弃 jQuery 来实现像触发点击这样简单的事情:

// replace this
$(window.parent.document.getElementById('click')).trigger('click');

// with this
window.parent.document.getElementById('click').click();

关于安全的注意事项:这是一种相当脆弱的方法,因为您必须知道父文档中存在具有该特定 id 属性的特定元素。在可能不存在的节点上调用 click 之前至少检查是否存在会更好。

关于javascript - 从 iframe 访问父页面的 id 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38517879/

相关文章:

javascript - 如何在 JavaScript 中使用 onblur 和 onchange

php - jquery cookie 插件还是 php cookie?

javascript - jQuery:按类更新带有日期选择器输入值的 span 标签?

c# 通过outlook 2013发送html电子邮件

html - 如何让下拉菜单覆盖其他元素

javascript - 制作表单传递参数

javascript - 无法在 firebase 函数中获取 setState

javascript - NodeJS/浏览器交叉开发

javascript - 如何实现youtube显示和隐藏令人难忘的侧边栏?

javascript - 使用knockoutjs将url内容加载到div上