我正在尝试使用 iframe 对象 和 jQuery 访问特定元素(可能与此更相似),但它不起作用。
iframeWindow
对象不为空 但下一条语句似乎不起作用。我看到了类似 this 的东西在这个答案上,但它不起作用。我做错了什么吗?
这是我的代码:
radio .PHP
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
setTimeout(function(){
var iframe= document.getElementById("iframe");
var iframeWindow = iframe.contentWindow;
var text=iframeWindow.$("div:nth-child(3) .c2").html();
console.log(text);
//DOESN'T PRINT "INNER MOST"
}, 1000);
});
</script>
</head>
<body>
<div class="c1">
<iframe id="iframe" src="api.php" height="200" width="300">
</iframe>
</div>
</body>
</html>
API.PHP
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<script type="text/javascript" src="jquery.js"></script>
<body id="abody">
Hey
<div class="c1"></div>
<div class="c1">
<p class="c2"></p>
</div>
<div class="c1">
<p class="c2">
INNER MOST
</p>
</div>
</body>
</html>
编辑:我已经纠正了语法错误。
最佳答案
您应该结合使用 iframe.contentWindow.document
而不是 iframe.contentWindow
与 find()
和 text()
它应该可以工作。试试这个:
$(document).ready(function() {
setTimeout(function() {
var iframe = document.getElementById("iframe");
var iframeWindow = iframe.contentWindow.document;
var text = $(iframeWindow).find(".c1:nth-child(3) .c2").text();
console.log(text);
//PRINTS "INNER MOST"
}, 1000);
});
根据 MDN 文档说:
The contentWindow property returns the Window object of an iframe element. You can use this Window object to access the iframe's document and its internal DOM. This attribute is read-only, but its properties can be manipulated like the global Window object.
您可以阅读有关 iframe 元素及其工作原理的更多信息 here .
关于javascript - 为什么我不能使用 iframe 对象和 jQuery 遍历这个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41544585/