【问题标题】:How to loop over iframes and set a src value based on name value?如何循环 iframe 并根据名称值设置 src 值?
【发布时间】:2018-09-04 01:43:07
【问题描述】:

我试图通过检查它们的属性(名称)来遍历所有现有的 iframe。如果它与名称匹配,我想设置一个src 值。

<iframe name="test1" src="" />
<iframe name="test2" src="" />
<iframe name="test3" src="" />

<script>
$(document).ready(function(e) {
var frames = document.getElementByTagName('iframe');
for (var i in frames) {
    if (frames[i].name.match(/test1/g)) {
       iframes[i].attr('src', 'http://testing1.com/');
    }
    if (frames[i].name.match(/test2/g)) {
       iframes[i].attr('src', 'http://testing2.com/');
    }
}
};
</script>

有人可以帮我修复代码以使其有效吗?

【问题讨论】:

  • 您有时调用变量frames,有时调用iframes

标签: javascript html iframe src


【解决方案1】:

如果这已经得到答案,我也会回答。就是这样,香草js:

var selection = document.getElementsByTagName('iframe');
var iframes = Array.prototype.slice.call(selection);

iframes.forEach(function(iframe) {
    if (iframe.name.match(/test1/g)) {
        iframe.setAttribute("src", "http://testing1.com/");
    } else if (iframe.name.match(/test2/g)) {
        iframe.setAttribute("src", "http://testing2.com/");
    } else if (iframe.name.match(/test3/g)) {
        iframe.setAttribute("src", "http://testing3.com/");
    }
});

JSFiddle here.

【讨论】:

    【解决方案2】:

    嗯,函数是 getElementsByTagName(复数形式)。您还将 jQuery 函数与本机 DOM 元素混合在一起,这是行不通的。但既然你无论如何都在使用 jQuery,那么你不妨将它用于所有代码:

    <script>
    $('iframe[name="test1"]').attr('src', 'testing1.com')
    $('iframe[name="test2"]').attr('src', 'testing2.com')
    </script>
    

    编辑:另外,iframe 不是自闭合标签,所以如果你像在帖子中那样使用 &lt;iframe /&gt;,你会得到奇怪的行为。您应该明确关闭标签:&lt;iframe&gt;&lt;/iframe&gt;

    【讨论】:

      【解决方案3】:

      一个工作示例;

      $(document).ready(function(e) {
      
        $('iframe').each(function() {
          if ($(this).attr('name') == "test1")
            $(this).attr('src', 'https://www.domain1.com');
          if ($(this).attr('name') == "test2")
            $(this).attr('src', 'https://www.domain2.com');
          if ($(this).attr('name') == "test3")
            $(this).attr('src', 'https://www.domain3.com');
        });
      });
      <iframe name="test1"></iframe>
      <br>
      <iframe name="test2"></iframe>
      <br>
      <iframe name="test3"></iframe>

      小提琴:https://jsfiddle.net/v760e5zq/

      【讨论】:

        猜你喜欢
        • 2018-07-16
        • 2016-10-09
        • 2017-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多