【问题标题】:jQuery iframe selector workings in dev tool but not in the pagejQuery iframe 选择器在开发工具中工作但不在页面中
【发布时间】:2017-09-30 05:20:30
【问题描述】:

有人能告诉我为什么以下行在开发工具控制台中有效,但在页面中无效,我一直将长度设为 0

$("iframe[name='gridFrame']").contents().find("form[name='grid']").length;

这是页面:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script type="text/javascript" src="/Scripts/jquery-3.1.1.js"></script>
    <script>

    $(function () {
        submitThis();

        function submitThis() {
            var a = $("iframe[name='gridFrame']").contents().find("form[name='grid']").length;
            console.log(a);
        }
     })
    </script>
</head>

<body>
    <iframe name="gridFrame" src="temp-iframe-test.html">
    </iframe>
</body>
</html>

这是 iframe 文件:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>

<body>
   <form name="grid">
     <input id="fname" />
   </form>

</body>
</html>

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    您的 submitThis() 函数在您的 iframe 加载其源代码之前触发。这就是为什么你会看到长度为 0。

    尝试添加: onload="submitThis()" 到您的 iframe 元素并将您的 submitThis 函数移动到全局范围(在 $ 函数之外)。

    使用开发控制台时,您的 iframe 已加载其文件。

    【讨论】:

    • 如果我不想在框架加载时提交表单,而是希望它在主窗口中通过某些操作触发怎么办?
    猜你喜欢
    • 2014-07-22
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多