开发者

$target = $(target) in javascript\jQuery. Need explanation of syntax

The sample code mentioned below is a part of jQuery Countdown plugin by Keith Wood. Can some explain this

_attachCountdown: function(target, options) {
        var $target = $(target);
        if ($target.hasClass(this.markerClassName)) {
            return;
        }
        $target.addClass(this.markerClassName);
        var inst = {options: $.extend({}, options),
            _periods: [0, 0, 0, 0, 0, 0, 0]};
      开发者_开发问答  $.data(target, PROP_NAME, inst);
        this._changeCountdown(target);
    }

Is there a reason specifically defining $target or its just same as our simple variables like var target.

Thanks in advance.


It is a simple variable, $ is just added to indicate to the code reader that a jQuery collection is stored inside. Javascript is quite "lenient" with variable names, the $ has no special meaning (opposed to PHP where it is needed before every variable name).

This method (var $target=$(target);) is used to save the result of $(target) (the jQuery collection itself, storing target) into a variable, so the jQuery collection does not need to be created everytime it is needed.


The $ in JavaScript is valid for variable names and has no significance on its functionality.

The original author was probably saving two keystrokes (or four if you include shift) and renaming it for convenience, but left the $ prefix to symbolize it is a jQuery-wrapped object. (Think of it like the old Hungarian Notation facsimile.)


By the following code:

var $target = $(target);

the author of the script assigns to the following variable:

$target

the result of the following expression:

$(target)

which is the result of jQuery() function ($() is only an alias for it) being passed the target variable.

So, to sum up, what you have here is:

  • target JS variable (probably some string determining the selector),
  • $ JS function (basically jQuery function, but the $ alias is often used for writing shorter code),
  • $target JS variable that stores the result of the $(target) (or jQuery(target)) expression
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜