Home > Web Front-end > JS Tutorial > How to get the value of an element in an iframe via JavaScript

How to get the value of an element in an iframe via JavaScript

一个新手
Release: 2017-10-11 09:25:17
Original
3053 people have browsed it

Requirements Analysis

If our project has two HTMLs a and b, how can a.html get the value of the element in b.html?

Specific implementation

b page has an input

<input name="hh" type="text">
Copy after login

a page HTML code:

<!-- HTML代码, src="指向地址" -->
<!-- 如果不需要b页面展示在a页面, display: none;添加CSS代码隐藏掉 -->
<iframe id="b" src="b.html" style="display: none;    "></iframe>
Copy after login

a page JavaScript code:

//为什么用 window.onload 下面会详解window.onload = function () {
    //先取到iframe         
    var b= document.getElementById("b");    //通过iframe取其b.html上的值           
    var hh= b.contentDocument.getElementsByName("hh")[0].value;    //弹出消息, 查看正确与否          
    alert(hh);

}
Copy after login

window.onload: Execute
$(document).ready(function(){}) after all resources of the page are loaded (equivalent to $## in jQuery #(function(){}) ): The DOM node of the page is created and executed If you use $(document).ready(function(){}), you will not get the value. Why? The answer is obvious:
Although the iframe node has been created, the page resources have not been loaded. However, the JS code is executed immediately, and the result is that the value cannot be obtained, and window.onload will wait until all the page resources are loaded before executing the JS code
Thanks for reading

The above is the detailed content of How to get the value of an element in an iframe via JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template