首页 > 解决方案 > 使用 jquery 或 javascript 在外部 iframe 中设置输入字段值

问题描述

我强烈面临 iframe 问题。我需要在其他 web 端的输入字段中设置值。我发布我的代码。我已经在检查contentDocument(返回 null)和contentWindow不起作用(捕获错误)任何人都可以帮助我。

我正在关注链接https://www.w3schools.com/jsref/prop_frame_contentwindow.asp

但我没有成功。当我检查console.log($('[name=name]'))浏览器控制台减损时,console.log($('[name=name]').value=4)然后使用错误。

当浏览器控制台测试使用相同的代码($('[name=name]').value=4)时,有时会设置值,有时会出错。

用于测试的完整代码发布

<html>
<head>
    <style>
    iframe{
        border: none;
        width: 100%;
        height: 100%;
    }
    </style>        
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
    <!-- <script  src="script/jquery-1.10.2.js?id=12"></script> -->
    <script>
        window.onload=function(){
            $("#btnLoad").on("click",function(){
                document.getElementById('ifUrl').src=$("#txtUrl").val();
                $("#btnFill").prop('disabled', true);
                document.getElementById("ifUrl").onload=function(){ 

                    setTimeout(function(){ $("#btnFill").prop('disabled', false); }, 5000)
                        $("#btnFill").on("click",function(){
                        var iframe = document.getElementById("ifUrl");
                        var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
                        //var text = $("#ifUrl").contents(); 
                        console.log(innerDoc);
                        //console.log($('#ifUrl'))
                        });
                    };

                //alert($("#txtUrl").val());
                // $("#ifUrl").load(function() {
                //    alert()
                //     //alert($(this).contents().find("html"))
                // });

            });


        }


    </script>
</head>
<body>
    <div>URL: 
        <input type="text" id="txtUrl" value="https://www.dsebd.org/contact.php"/>
    </div>
    <div>
        <button id="btnLoad" type="button">Load Url</button>
        <button id="btnFill" type="button" disabled="true">Fill Up</button>
    </div>
    <div>
        <iframe id="ifUrl">

        </iframe>
    </div>
</body>

标签: javascriptjquery

解决方案


推荐阅读