【问题标题】:Jquery read parent value from iframeJquery 从 iframe 读取父值
【发布时间】:2016-11-22 19:39:38
【问题描述】:
我正在尝试读取 iframe 之外的用户名。如何在 iframe 内单击按钮时将父值从 iframe 中取出?
Here is my fiddle
<span id="user">
My Name
</span>
<iframe id="my-iframe" height=200 width=300>
<input type="button" id="myButton" value="click">
</iframe>
$('#myButton').click(function(){
var userName = $('#user').text();
alert(userName);
});
【问题讨论】:
标签:
javascript
jquery
html
iframe
【解决方案1】:
我不知道你可以拥有一个没有源的 iFrame,but apparently you can。我不确定您为什么要这样做,但似乎您必须写入 iFrame 本身,而不是将元素嵌套在其中。例如:
var iframe = $("#my-iframe")[0].contentWindow.document;
$("body", iframe).html("<input type=\"button\" id=\"myButton\" value=\"click\">");
请注意,如果父项和子项位于 same domain and protocol 上,则您只能访问 iFrame 的内容。我猜你的情况下的 iFrame“文字”被视为同一来源。
另外,由于您的点击绑定是在父窗口中运行的,它只在父文档中搜索元素。您必须调整您的选择器,以便它搜索 iframe 文档:
var iframe = $("#my-iframe")[0].contentWindow.document;
$("#myButton", iframe).click(function(){
var userName = $("#user").text();
alert(userName);
});
同源政策同样适用于上述情况。
完整的小提琴here。