2016-07-19 61 views
0

我想读取一个用户名是外侧iframe。如何在单击iframe内的按钮时获取父级值的iframe?jquery从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); 
}); 

回答

1

我不知道,你可以有一个iFrame没有来源,but apparently you can。我不知道你为什么这样做,但似乎你必须写入iFrame本身,而不是嵌套在里面的元素。例如:

var iframe = $("#my-iframe")[0].contentWindow.document; 

$("body", iframe).html("<input type=\"button\" id=\"myButton\" value=\"click\">"); 

请注意,您只能访问一个iframe的内容,如果家长和孩子都在same domain and protocol。我想在你的情况下,iFrame“字面量”被视为相同的原点。

此外,由于您的点击绑定在父窗口中运行,因此它仅在父文档中搜索元素。这样它搜索的iframe文档而不是你必须调整你的选择:

var iframe = $("#my-iframe")[0].contentWindow.document; 

$("#myButton", iframe).click(function(){ 
    var userName = $("#user").text(); 
    alert(userName); 
}); 

同源策略适用于以上为好。

小提琴here

相关问题