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

问题描述 投票:1回答:3

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

有人会帮我修改代码使其有效吗?

javascript html iframe src
3个回答
2
投票

好吧,函数是getElementsByTagName(复数形式)。您还将jQuery函数与本机DOM元素混合在一起,这将无法正常工作。但是既然你正在使用jQuery,你也可以将它用于所有代码:

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

编辑:同样,iframe不是自动关闭标签,所以如果你像在帖子中那样使用<iframe />,你会得到奇怪的行为。你应该明确地关闭标签:<iframe></iframe>


2
投票

如果这已经得到答案我也在回答。这就是它,vanilla 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


0
投票

一个工作的例子;

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

© www.soinside.com 2019 - 2024. All rights reserved.