如何循环 iframe 并根据名称值设置 src 值?

How to loop over iframes and set a src value based on name value?

我试图通过检查它们的属性(名称)来遍历所有现有的 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>

谁能帮我修改代码使其有效?

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

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

编辑:此外,iframe 不是自动关闭标签,因此如果您像在 post 中那样使用 <iframe />,将会出现奇怪的行为。您应该明确关闭标签:<iframe></iframe>

一个工作示例;

$(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>

Fiddle: https://jsfiddle.net/v760e5zq/

如果这已经得到答案,我也会回答。就是这样,香草 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.