开发者

Placing a couple of custom Jquery Functions into an external Script

开发者 https://www.devze.com 2023-01-18 19:18 出处:网络
I have the following two functions and i need help moving these into an external file. $.fn.clearSelect = function () {

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

精彩评论

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

关注公众号