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.
精彩评论