在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" ></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  />  
    </div>  
</body>  
</html>  

 

相关文章:

  • 2021-08-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-18
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-05-20
  • 2021-10-14
  • 2021-08-20
  • 2021-07-22
  • 2022-12-23
相关资源
相似解决方案