2012-01-02 22 views
0
使用

是否有可能宣佈在varjquery.live()(以及.delegate() & .on()),它可以在所有的函數中使用?申報VAR(),它可以在所有功能

例子:

$("#s4-leftpanel-content ul.root > li.static > a").live({ 
    click: function (event) { 
     var hasChildren = $(this).parent('li').children('ul').length > 0; 
     if (hasChildren) { 
      event.preventDefault(); 
      $("#s4-leftpanel-content ul.root li.static > ul.static").hide(); 
      $(this).parent('li').children('ul').toggle(); 
     } 
    }, 
    mouseover: function() { 
     $(this).css('background-color', 'green'); 
    }, 
    mouseout: function() { 
     $(this).css('background-color', ''); 
    } 
}); 

可以說,我想用布爾VAR hasChildrenmouseovermouseout功能以及,我則必須聲明,var又在這兩個函數或者是有辦法我可以在這個當前對象中全局地聲明它?

回答

5

變量是局部的背景下,在這種情況下,事件處理程序。

你有三種可能性:

的所有事件處理程序

例如創建一個範圍可達變量:

(function() { 
    var hasChildren; 

    $("#s4-leftpanel-content ul.root > li.static > a").live({ 
     // ... 
     mouseover: function() { 
      hasChildren = $(this).parent('li').children('ul').length > 0; 
      $(this).css('background-color', 'green'); 
     }, 
     //... 
    }); 
}()); 

自調用函數創建一個新的範圍。 hasChildren只能由事件處理程序訪問,不會泄漏到全局範圍內。

使用.data()[docs]

.data()可以讓你隨心所欲的數據附加到DOM元素。

//... 
click: function (event) {  
    var hasChildren = $(this).data('hasChildren'); 
    if (hasChildren) { 
     event.preventDefault(); 
     $("#s4-leftpanel-content ul.root li.static > ul.static").hide(); 
     $(this).parent('li').children('ul').toggle(); 
    } 
}, 
mouseover: function() { 
    $(this).data('hasChildren', $(this).parent('li').children('ul').length > 0); 
    $(this).css('background-color', 'green'); 
}, 
//... 

更新:

由於@pimvdb指出,如mouseover總是click之前觸發,你可以在你的mouseover事件處理程序分配的值,然後通過$(this).data('hasChildren')訪問它在其他任何處理程序或只是hasChildren,這取決於您選擇哪種方式(更改代碼以反映此情況)。

因素進行計算

由於該元素是否有子女或不僅取決於元素本身,你還可以分析出該行代碼放到一個額外的功能,並調用它在每一個事件的決心處理程序:

(function() { 
    function hasChildren(element) { 
     return $(element).parent('li').children('ul').length > 0; 
    } 

    $("#s4-leftpanel-content ul.root > li.static > a").live({ 
     click: function (event) {  
      var hc = hasChildren(this); 
      // .. 
     }, 
     mouseover: function() { 
      var hc = hasChildren(this); 
      $(this).css('background-color', 'green'); 
     }, 
     //... 
    }); 
}()); 

當然這與重複相同的計算的代價,但你至少不重複代碼。

+2

雖然這在技術上是正確的,但我認爲這不合理,因爲''click''之前'mouseover'被觸發*。據我瞭解,OP希望在所有處理程序中執行'hasChildren'代碼而不復制它。 – pimvdb 2012-01-02 10:29:32

+0

@pimvdb:哦,現在我明白了......謝謝! – 2012-01-02 10:32:07

0

在像頂部聲明你的變量:與var宣佈

 

<script type="text/javascript"> 
var hasChildren; 
//then your js, jQuery codes 
</script> 
 
相關問題