Sha*_*nky 6 html javascript php iframe jquery
我正在尝试使用iframe对象和jQuery访问特定元素(可能更类似于此),但它无法正常工作.
该iframeWindow对象不为null,但下一个语句似乎不起作用.我看到的东西像这样在这个答案,但它不工作.难道我做错了什么?
这是我的代码:
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>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
编辑:我已经纠正了语法错误.
您应该使用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);
});
Run Code Online (Sandbox Code Playgroud)
根据MDN文档说:
所述contentWindow属性返回窗口的对象的iframe元件。您可以使用此 Window 对象访问 iframe 的文档及其内部DOM。此属性是只读的,但可以像全局 Window 对象一样操作其属性。
您可以在此处阅读有关 iframe 元素及其工作原理的更多信息。