使用jQuery将类添加到iframe中的元素

时间:2010-10-21 19:26:28

标签: jquery iframe

<iframe src="/demo.php" id="source"></iframe>

$('#source').delegate('*', 'hover', function() {
    $(this).addClass('hover');  
});

$('#source').delegate('*', 'mouseout', function() {
    $(this).removeClass('hover');   
});

$('#source').delegate('*', 'click', function() {
    alert($(this).html());
    return false;
});

当我鼠标悬停或点击Iframe内的任何元素时,没有任何反应。 Iframe位于同一个域中,而且我的印象是,只要Iframe src位于同一个域上,就应该有效。

关于如何使这项工作的任何想法?

2 个答案:

答案 0 :(得分:6)

最终编辑:

有两个问题:

  1. 使用$('#source').contents()而不是简单地使用$('#source')

  2. 在iframe的上下文中,.hover的css规则不可见 可以使用.css()直接设置样式,在demo.php中添加css链接,或者使用jQuery将主文档中的所有样式克隆到iframe中。

  3. 另外你应该避免使用.live,因为iframe中似乎有some issue个(当使用实时jQuery时会绑定文档上的特殊eventHandlers,并在事件冒出时检查事件)

    以下是一个工作示例(jsFiddle link):

    var $c = $('#source').contents();
    
    //clone all styles from this document into the iframe
    $c.find('head').append($('style, link[rel=stylesheet]').clone());
    
    $c.find('body').prepend('<b>This is a test</b><br><b>Click here</b>');
    
    $c.delegate('b', 'hover', function() {
        $(this).toggleClass('hover');
    });
    
    $c.delegate('b', 'click', function() {
        alert('You clicked on:' + $(this).text());
    });
    

    原始答案:

    您的问题是您使用iframe作为上下文。您应该使用框架文档。

    另外,为了安全起见,您可能希望在onload事件中添加代码,如下所示:

    var doc = window.frames['source'].document;
    $(doc).ready(function(){
        $('body').prepend('This is outside the iframe<br>');
        $('body',doc).prepend('This is inside the iframe<br>');
    });
    

    您可以查看此live jsFiddle example


    编辑1:

    好的,所以实际问题是在iframe中看不到css样式。

    例如,如果您使用$(this).css('color':'red')代替addClass,则可以使用。请参阅更新的jsFiddle

    我建议要么在demo.php中有正确的css样式,要么在之后插入如下:

    $('head',doc).append($('style, link[rel=stylesheet]').clone());
    

    updated jsFiddle - 使用addClass和克隆样式

答案 1 :(得分:0)

尝试使用此contents

demo.php:

<html>
<head>
...
</head>
<body>
<div id="container-div">
...
</div>
</body>
</html>

代码:

<iframe src="/demo.php" id="source"></iframe>

$('#source').contents().delegate('container-div', 'hover', function() {
    $(this).addClass('hover');  
});

$('#source').contents().delegate('container-div', 'mouseout', function() {
    $(this).removeClass('hover');   
});

$('#source').contents().delegate('container-div', 'click', function() {
    alert($(this).html());
    return false;
});