开发者

Placing a couple of custom Jquery Functions into an external Script

I have the following two functions and i need help moving these into an external file.

 $.fn.clearSelect = function () {
        return this.each(function () {
            if (this.tagName == 'SELECT')
                this.options.length = 0;
        });
    }

    $.fn.addItems = function(data) {
        return this.each(function () {
            var list = this;
            $.each(data, function (index, itemData) {
                var option = new Option(itemData.Text, itemData.Value);

                list.add(option);
            });
        });
    }

Is there something special that i would need to do? I've attempted to do this by myself and i came up with the following, but i'm getting the an "Uncaught SyntaxError: Unexpected token )".

(function ($) {
    clearSelect = function () {
        return this.each(function () {
            if (this.tagName == 'SELECT')
                this.options.length = 0;
        });
    };

    addItems = function (data) {
        return this.each(function () {
            var list = this;
            $.each(data, function (index, itemData) {
                var option = new Option(itemData.Text, itemData.Value);
                list.add(开发者_JAVA百科option);
            });
        });
    };
})(jQuery);

Thanks


Your initial approach should work...just make sure the file is included after jQuery itself. You can test it here.

Another option is to extend $.fn similar to your second attempt, like this:

(function($) {
  $.fn.extend({
    clearSelect: function() {
      return this.each(function() {
        if (this.tagName == 'SELECT') this.options.length = 0;
      });
    },
    addItems: function(data) {
      return this.each(function() {
        var list = this;
        $.each(data, function(index, itemData) {
          var option = new Option(itemData.Text, itemData.Value);
          list.add(option);
        });
      });
    }
  });
})(jQuery);

You can test that version here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜