繁体   English   中英

JavaScript中“ typeof $”的含义是什么?

[英]What is meaning of “typeof $” in javascript?

以下源代码中typedef $的含义是什么。 我已从此链接中阅读。

typeof允许标识符从未被声明过。 因此,在这方面更安全:

但是这里他们使用if (typeof $ !== 'undefined') ,这里$含义是什么。

我从此链接复制了以下代码

<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>

在Javascript中, $只是一个变量名,因此:

if (typeof $ !== 'undefined')

只是检查以查看$变量是否已经定义。 在使用jQuery的代码中, $符号通常是jQuery对象的别名,因此此代码将检查是否存在jQuery或jQuery是否使用$符号。

您没有向我们展示addHorizonLoadEvent()代码,但是逻辑表明它可能负责加载jQuery或了解何时包括jQuery的一组东西完成加载,如果代码发现加载$任何东西,就可以使用它。尚未完成加载。

在您的情况下,作者只是检查是否存在某些库并已加载它们:

  • (typeof $ !== 'undefined') ->使用$的库(在您的情况下$ JQuery)
  • (typeof horizon.d3_line_chart != 'undefined') ->图表库?

如果已加载库,则可以执行一些代码;如果未加载库,则不会崩溃。 如果不存在一个库,也可以尝试使用另一个库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM