如何从 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/