2015-06-23 51 views
0

在以下源代碼中,typedef是$的含義。我已閱讀this link

typeof允許標識符永遠不會被聲明。所以在這方面比較安全:

但是這裏他們使用的是if (typeof $ !== 'undefined'),這裏$的含義是什麼。

我複製下面的代碼從this link

<script type="text/javascript"> 
    if (typeof horizon.d3_line_chart !== 'undefined') { 
    //alert("test1"); 
    //When first time It give alert means it is defiend 
    horizon.d3_line_chart.init("div[data-chart-type='line_chart']", 
     {'auto_resize': true}); 
    } 

    if (typeof $ !== 'undefined') { 
    //alert("alert2"); 
    /* 
     We first time we run resource usage, then It will show alert, and date options are not showing. So means first time It hides the date options. Means '$' varaible is defined. 
    */ 
    show_hide_datepickers(); 
    } else { 
    addHorizonLoadEvent(function() { 
     show_hide_datepickers(); 
    }); 
    } 

    function show_hide_datepickers() { 
    $("#date_options").change(function(evt) { 
     // Enhancing behaviour of selectbox, on 'other' value selected, I don't 
     // want to refresh, but show hide the date fields 
     if ($(this).find("option:selected").val() == "other"){ 
      evt.stopPropagation(); 
      $("#date_from input, #date_to input").val(''); 
      $("#date_from, #date_to").show(); 
     } else { 
      $("#date_from, #date_to").hide(); 
     } 
    }); 
    if ($("#date_options").find("option:selected").val() == "other"){ 
     $("#date_from, #date_to").show(); 
    } else { 
     $("#date_from, #date_to").hide(); 
    } 
    } 
</script> 
+0

當然要確保JQuery(或另一個庫?)被加載並綁定到'$' –

+0

@MichaelLaffargue,謝謝你的回覆,以及'typeof horizo​​n.d3_line_chart!=='undefined''的含義是什麼 – geeks

+0

檢查horizo​​n.d3_line_chart類是否包含在內 –

回答

3

在Javascript中,$僅僅是一個變量名稱,以便:

if (typeof $ !== 'undefined') 

只是檢查,看看是否$變量已被定義或沒有。在使用jQuery的代碼中,$符號通常是jQuery對象的別名,因此此代碼將檢查jQuery是否存在,或者jQuery是否使用了$符號。

您不會向我們展示addHorizonLoadEvent()代碼,但邏輯會建議它可能負責加載jQuery或知道何時包含jQuery的一組內容已完成加載,並且如果代碼發現任何內容加載$尚未完成加載。

0

在你的情況,作者只檢查如果一些庫存在和裝載:

  • (typeof $ !== 'undefined') - >(你的情況的JQuery)使用$
  • (typeof horizon.d3_line_chart != 'undefined') - >的圖表圖書館?

這允許一些代碼,如果一個庫被加載,並不會崩潰,如果它不是。也可以用來使用不同的庫,如果不存在的話嘗試另一個庫。