我试图通过检查它们的属性(名称)来遍历所有现有的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不是自动关闭标签,所以如果你像在帖子中那样使用<iframe />
,你会得到奇怪的行为。你应该明确地关闭标签:<iframe></iframe>
如果这已经得到答案我也在回答。这就是它,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。
一个工作的例子;
$(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>