javascript 在 iframe 中获取带有 class 的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12145958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:26:01  来源:igfitidea点击:

Take elements with class inside iframe

javascriptjqueryiframeinternet-explorer-8

提问by Halfist

I have several iframes on the page. There are some elements with classname testinside of them. I need to set any styleto them.

iframe在页面上有几个。其中有一些带有类名的元素test。我需要style为他们设置任何。

When I have only one iframe, I can use next construction:

当我只有一个时iframe,我可以使用下一个构造:

$('#iframeId').contents().find('.test').css({background: '#f00'});

But I have several iframes, so it would be great not to set concrete iframeand use construction like:

但是我有几个iframes,所以最好不要设置混凝土iframe并使用如下结构:

$('.test').css({background: '#f00'});

But it doesn't work, of course.

但这当然行不通。

I used native getElementsByClassNamebefore, but it doesn't work in IE8, where defect appears.

getElementsByClassName之前用过原生的,但是在IE8出现缺陷的 .

It may be stupid question, but.. Is there any construction like:

这可能是一个愚蠢的问题,但是.. 有没有像这样的结构:

$(getElementById('something')).css({background: '#f00'});

It would be very helpful. I mean, wrap JavaScriptobject with jQueryand then use jQuerymethods with them.

这将非常有帮助。我的意思是,用 包装JavaScript对象,jQuery然后jQuery对它们使用方法。

Update:I solved this problem with next construction:

更新:我用下一个构造解决了这个问题:

[].forEach.call(document.getElementById('something').querySelectorAll('.test'), function (el) {
    el.style.backgroundColor = '#f00';
});

But it's still doesn't work for IE8.

但它仍然不适用于IE8.

回答by Kundan Singh Chouhan

You should try some thing like this

你应该尝试这样的事情

$("iframe").each(function(index){
   $(this).contents().find('.test').css({background: '#f00'});
});

Hope this will help you.

希望这会帮助你。

回答by MaxPRafferty

You may be running into one of two issues: 1) You are generally not able to modify the contents of iFrames returned from external domains, though that may not be the case here. If your iframes are pointing within your domain you should be fine. 2) ie8 has know problems with the "innerHTML" property, which jQuery's .css may rely on. instead, try using DOM methods:

您可能会遇到以下两个问题之一:1) 您通常无法修改从外部域返回的 iFrame 的内容,但此处可能并非如此。如果您的 iframe 指向您的域内,您应该没问题。2) ie8 知道 jQuery 的 .css 可能依赖的“innerHTML”属性的问题。相反,请尝试使用 DOM 方法:

document.getElementById("yourIframe").contentWindow.document.body.getElementById("innerIframeElement").setAttribute("style", "background:'#f00';"