If our project has two HTMLs a and b, how can a.html get the value of the element in b.html?
b page has an input
<input name="hh" type="text">
a page HTML code:
<!-- HTML代码, src="指向地址" --> <!-- 如果不需要b页面展示在a页面, display: none;添加CSS代码隐藏掉 --> <iframe id="b" src="b.html" style="display: none; "></iframe>
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); }
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!