爱程序网

如何获得iframe中元素的值

来源: 阅读:

在Web开发时,很多时候会遇到一个问题。我在一个页面嵌入了iframe,并且我想获得这个iframe页面某个元素的值。那么该如何实现这个需求呢?

iframe1中文本框的值:

在IE下操作IFrame内容的代码:

document.frames["MyIFrame"].document.getElementById("s").style.color="blue";

 

但是这在Firefox下无效。所以,想到在Firefox下用FireBug来调试。经过调试发现在Firefox下可用以下代码来实现:

document.getElementById("MyIFrame").contentDocument.getElementById("s").style.color="blue";

 

demo代码:

复制代码
    <div><iframe name="frame1" id="frame1" src="frm.html" frameborder="1" height="60"></iframe></div>  
    
    <p>iframe1中文本框的值:<input type="button" name="Submit" value="getValue" onclick="getValue()" /></p>  
      
<script type="text/javascript">  
function getValue()  
{  
    var ofrm1 = document.getElementById("frame1").document;      
    if (ofrm1==undefined)  
    {  
        ofrm1 = document.getElementById("frame1").contentWindow.document;  
        var ff = ofrm1.getElementById("txt1").value;  
        alert("firefox/chrome取值结果为:" + ff);  
    }  
    else  
    {  
        var ie = document.frames["frame1"].document.getElementById("txt1").value;  
        alert("ie取值结果为:" + ie);  
    }   
}  
</script>  
复制代码

 

 iframe页面代码:
复制代码
<html>  
<head>  
    <title>框架内页</title>  
</head>  
<body>  
    <div>  
        <input id="txt1" name="txt1" type="text" value="欢迎访问www.nowamagic.net" />  
    </div>  
</body>  
</html>  
复制代码

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助