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

Dav*_* B. 1 iframe jquery

<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;
});
Run Code Online (Sandbox Code Playgroud)

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

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

Dan*_*anu 6

最终编辑:

有两个问题:

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

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

另外你应该避免,.live因为iframes中似乎存在一些问题(当使用live jQuery绑定文档上的特殊eventHandlers时,并在它们冒泡时检查事件)

这是一个工作示例(jsFiddle链接):

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());
});
Run Code Online (Sandbox Code Playgroud)

原始答案:

您的问题是您使用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>');
});
Run Code Online (Sandbox Code Playgroud)

您可以查看此实时jsFiddle示例.


编辑1:

好吧,实际问题是在iframe中看不到css样式.

例如,如果您使用$(this).css('color':'red')而不是addClass它将起作用.查看更新的jsFiddle

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

$('head',doc).append($('style, link[rel=stylesheet]').clone());
Run Code Online (Sandbox Code Playgroud)

更新了jsFiddle - 使用addClass和克隆样式