CSe*_*eem 1 html javascript iframe src
我试图通过检查它们的属性(名称)来循环所有现有的 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>
Run Code Online (Sandbox Code Playgroud)
有人能帮我修复代码以使其有效吗?
如果这已经得到答案,我也会回答。就是这样,香草 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/");
}
});
Run Code Online (Sandbox Code Playgroud)
JSFiddle在这里。