使用getElementsByClassName迭代DOM元素的正确方法是什么



我希望我的用户能够访问移动模拟器,这样他们就可以测试他们网站的响应能力。我正在使用类似responsinator的iframe方法。在这里和这里做了研究之后,我不太确定我应该选择哪条路线。。。我正在尝试一个不起作用的代码。

表单输入

  Enter the link of your website below
            <form method="post" target="browser" style="padding-top:50px;">
<input  id="txtUrl" style="width:60%; display:inline-block; margin-top:10px; height:100%;" placeholder="eg. http://www.google.com/" name="url" type="text" />
<input style="display:inline-block; height:100%; border-radius:45%;"  type="button" value="Go" onclick="setBrowserFrameSource(); return false;"/>
</form>

这只适用于一个iframe:

<script type="text/javascript">
    function setBrowserFrameSource(){
        var browserFrame = document.getElementById("browser");
        browserFrame.src= document.getElementById("txtUrl").value;
    }
</script>

 <div id="iPhone5-portrait" class="device-block">
           <h5>iPhone 5 portrait · width: 320px</h5>
          <iframe id="browser" name="browser" src="http://google.com" style="height:568px; width:320px"></iframe>
           </div>

这不适用于多个:

<script type="text/javascript">
    function setBrowserFrameSource(){
        var browserFrame = document.getElementsByClassName("browser");
        for(var i=0; i<browserFrame.length; i++)
                {
                    alert(browserFrame[i].innerHTML);
                }
        browserFrame.src= document.getElementById("txtUrl").value;
    }
</script>

  <div id="iPhone5-portrait" class="device-block">
           <h5>iPhone 5 portrait · width: 320px</h5>
          <iframe class="browser" name="browser" src="http://google.com" style="height:568px; width:320px"></iframe>
           </div>
           <div id="iPhone5-landscape" class="device-block">
         <h5>iPhone 5 landscape · width: 568px</h5>
          <iframe class="browser" name="browser" src="http://google.com" style="height:320px; width:568px"></iframe>
           </div>

这就是解决方案:

    for(var i=0; i<browserFrame.length; i++) {
       alert(browserFrame[i].innerHTML);
       browserFrame[i].src= document.getElementById("txtUrl").value;
    }

相关内容

最新更新