【问题标题】:Selecting an element in an iframe which is dynamically created by external script选择由外部脚本动态创建的 iframe 中的元素
【发布时间】:2014-04-18 08:17:48
【问题描述】:

我有一个图库,单击照片时会打开一个模式窗口。有一个 div #sbox-content 是空的,当点击照片时,外部脚本会动态地将一个 iframe 附加到这个 div。

我需要在这个 iframe 完全加载后选择 h2 元素。

到目前为止我已经尝试过什么(更改颜色只是为了查看它是否被正确选择):

jQuery(document.body).on('DOMNodeInserted', 'iframe', function() {
    jQuery('h2.item-title').css({
        color: '#FF0000'
    })
});

和:

jQuery('iframe').load(function() {
    jQuery('h2.item-title').css({
        color: '#FF0000'
    })
});

和:

jQuery('iframe').load(function() {
    jQuery(this).contents().find('h2.item-title').css({
        color: '#FF0000'
    })
});

没有任何效果... 是我做错了什么,还是整个方法都不对?

【问题讨论】:

  • 你试过$(document).on("load", "iframe", function...吗?

标签: javascript jquery html iframe


【解决方案1】:

试试这个:

jQuery(document).on('load','iframe',function() {
    jQuery(this).find('h2.item-title').css({
        color: '#FF0000'
    })
}).load();

【讨论】:

  • 不幸的是,仍然一无所获。
  • 我认为 h2 有问题。你有

    还是在 h2 里面有 item-title 类???

  • 是的,我有

    。但即使使用 find('h2') 也不起作用。我认为这与 iframe 在单击照片之前在 DOM 中不存在并且 jQuery(document).on('load', 'iframe'... 在这里没有帮助跨度>

  • 如我所想:jQuery(document).on('load','iframe',function() {console.log('iframe loaded');});不起作用。
  • 当然你应该在 document.ready 函数中绑定这些函数......
【解决方案2】:

这是一个使用 javascript 的代码(没有库)。

编辑

var newInterval;

newInterval = setInterval(function(){

if(typeof document.getElementById('sbox-content') != 'undefined' && document.getElementById('sbox-content') != null){

clearInterval(newInterval);

document.getElementById('sbox-content').onclick = function(){

checkifIframeExists();

}

}

},2000);

如果 div#sbox-content 内只有 1 个 iframe 并且 DOM 加载完成时

function checkifIframeExists(){

iframe_ = document.getElementById('sbox-content').getElementsByTagName('iframe')[0];

iframe_.onload = function(){

if(this.contentDocument){ response = this.contentDocument; }else{ response = this.contentWindow.document; }

//So, with the above code we already have the content of the loaded iframe 

h2els = response.getElementsByTagName('h2');

if(h2els.length==1){

//now we are setting/changing the first h2 element's text color

h2els[0].style.color = '#FF0000';

}else{

//or if there is more than one h2 element, we loop through all the h2 elements and find the one with class 'item-title' and changing its color

for(var i=0;i<h2els.length;i++){

if(h2els[i].className == 'item-title'){

h2els[i].style.color = '#FF0000';

}

}

}

}
}

【讨论】:

  • 正如我提到的,iframe 甚至不存在于 DOM 中。它是由外部画廊插件动态添加的,我无法修改。而且当 iframe 添加到 DOM 时,它仍然没有 id。连一堂课都没有。但它总是附加到 div #sbox-content
  • @zorza,div #sbox-content 中是否只有 1 个 iframe?
  • 是的,只有一个,但重要的是 iframe 内的内容可能会发生变化(通过 iframe 内的 nex/prev 按钮浏览照片)。
  • 但是您只针对该 iframe 中的 h2 元素,不是吗?每当点击其中一张照片时,都会调用 iframe,不是吗?你有什么活生生的例子吗?
  • 我已经在网上解决了这个问题。请查看问题的编辑版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-12
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-05
  • 2019-05-28
相关资源
最近更新 更多