2012-08-12 25 views
0

在下面的标记中,#enable按钮将向#show div添加一个类。这个类有一个附加的方法,淡入/淡出#hidden范围。如何在类添加到元素后触发类定位方法?

但是,即使将该类添加到#show div中,也不会触发附加到该类的方法。

HTML

<input type='button' id='enable' value='Enable' /> 

<div id='show'> 
Testing.. <span id='hidden'>Testing, 1, 2, 3.</span> 
</div>​ 

JS

$(function() { 

    // Adds .testing class after the button is clicked. however.. 
    $('#enable').click(function() { 
     $('#show').addClass('testing') 
    }); 

    // It will not trigger after .testing class has been added to DIV?    
    $('.testing').hover(function() { 
     $('#hidden').fadeIn(); 
    }, function() { 
     $('#hidden').fadeOut(); 
    }); 
});​ 

提琴工作,并具:http://jsfiddle.net/jS3nM/

看来我概念失去了一些东西。处理这个问题的正确方法是什么?

回答

2

jQuery的不像CSS一样工作,$("selector"),它会返回文档中与此选择器匹配的元素列表

然后,您将使用jQuery方法对这些元素进行操作,没有像“class-有针对性的方法“正在进行中

你可以找到一个事件侦听器添加到document

$(document).on({ 
    mouseenter: function() { 
     $('#hidden').fadeIn(); 
    }, 
    mouseleave: function() { 
     $('#hidden').fadeOut(); 
    } 
}, ".testing"); 

document总是发现始终存在,并且事件监听器被添加到这一点。最后的选择器筛选出哪些元素适合该事件。

+0

如果方法是jQuery的'resizable'或'draggable'方法,它包含选项如何处理? – Josh 2012-08-12 21:52:36

+0

@您需要在没有调用该方法的元素上调用该方法。在元素中思考,而不是选择器。当您创建需要调整大小的新元素时,您需要调用其大小。没有什么更多。 – Esailija 2012-08-12 21:53:15

+0

我想我明白了,但是我对一个需要选项的事件的语法感到困惑。例如,而不是'mouseenter',我会使用'resizable'。因此,'$(document).on({resizable:/ *如何添加选项?* /},'.testing');' – Josh 2012-08-12 21:58:31

1

因为当你绑定hover处理程序存在与文档类的testing没有元素,你应该委托的情况下,你可以使用on方法,请尝试以下”

$(document).on('mouseenter', '.testing', function(e) { 
     $('#hidden').fadeIn(); 
}); 

$(document).on('mouseleave', '.testing', function(e) { 
     $('#hidden').fadeOut(); 
}); 
+0

如何处理它的方法是jQuery的'resizable'或'draggable'方法,其中包括选项? – Josh 2012-08-12 21:50:54

+0

@Chase对于'resizable'和'draggable'方法,情况并非如此,因为它们不是事件,你可以选择目标元素并简单地调用方法。 – undefined 2012-08-12 21:56:53

+1

请注意,从v1.8开始''“hover”'作为''mouseenter mouseleave''的缩写已被弃用。 ('.hover()'函数没有被弃用,尽管它不适用于当前的问题。) – nnnnnn 2012-08-12 22:04:11