jQuery悬停不起作用

ano*_*ous 1 jquery hover

我希望jQuery在我悬停一个元素后做一些事情并在鼠标上执行其他操作.

我写了这个:

   jQuery('.item').hover(

        function() {
            var bg = jQuery(this).attr('data-background'); 
            jQuery(this).css("background-color", bg);
        }, 

        function() { /* this doesn't seem to work */
             alert(bg);  
        });
Run Code Online (Sandbox Code Playgroud)

你能告诉我为什么这个代码在第二个函数之前工作正常,所以它从不提醒任何东西?我相信有一个错字,但我找不到; /

Fel*_*ing 11

好吧,bg没有在第二个函数中定义.它只在第一个本地.这将有效:

jQuery('.item').hover(
    function() {
        var bg = jQuery(this).attr('data-background'); 
        jQuery(this).css("background-color", bg);
    }, 
    function() {
         var bg = jQuery(this).attr('data-background'); 
         alert(bg);  
});
Run Code Online (Sandbox Code Playgroud)

DEMO

为了公平对待upvotes,你可能也定义了bg由两个功能访问的范围:

(function() {
    var bg;
    jQuery('.item').hover(
        function() {
            bg = jQuery(this).attr('data-background'); 
            jQuery(this).css("background-color", bg);
        }, 
        function() {
            alert(bg);  
    });
 }());
Run Code Online (Sandbox Code Playgroud)

这里立即函数创建一个新范围(因此bg不会污染全局范围).但是否这是必要的取决于你真正想做什么.

DEMO


在jQuery 1.4.3中,您可以访问data-background使用也.data():

var bg = jQuery(this).data('background'); 
Run Code Online (Sandbox Code Playgroud)