javascript - 为什么我不能使用 iframe 对象和 jQuery 遍历这个元素?

标签 javascript php jquery html iframe

我正在尝试使用 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.contentWindowfind()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/

相关文章:

php - 使用 json 发送邮件

javascript - Phonegap 3.0.0 所有请求 404

javascript - Call() 方法无法在 JavaScript 中生成输出

javascript - 无法使用ajax添加评论

javascript - 使用 raphaeljs javascript 图形库清除容器的最简单方法

php - 使用三元运算符的 echo 中的 if 语句

php - 为什么PHP更新数据没有被选中?

javascript - 使用 jQuery 将值从文本框提供给变量

javascript - 根据单击的单选按钮更改 'li' css 样式

javascript - 如何遍历 JSON obj 的属性?