我正在修改一個jQuery插件。jQuery插件:可公開訪問的函數?
該插件是一個標籤系統,基於jQuery UI的自動完成自動完成。
目前似乎沒有辦法(除了解析創建的列表項)來找出哪些標籤已被選中。
我修改了插件,以便它管理一個名爲tags的數組,它包含列表。
但現在我需要一種方法來到數組。
來初始化它你叫
$('#id').tagit({availableTags: 'tags.php'});
我希望能夠做的是調用像
$('#id').tagit('tags');
或$('#id').tagit().tags();
得到的標記列表。
如何修改此代碼以添加該功能?
(function($) {
$.fn.tagit = function(options) {
var tags = [];
var defaults = {
availableTags: [],
allowSpace: false
};
var options = $.extend(defaults, options);
var el = this;
const BACKSPACE = 8;
const ENTER = 13;
const SPACE = 32;
const COMMA = 44;
// add the tagit CSS class.
el.addClass("tagit");
// create the input field.
var html_input_field = "<li class=\"tagit-new\"><input class=\"tagit-input\" type=\"text\" /></li>\n";
el.html(html_input_field);
tag_input = el.children(".tagit-new").children(".tagit-input");
$(this).click(function(e) {
if (e.target.tagName == 'A') {
// Removes a tag when the little 'x' is clicked.
// Event is binded to the UL, otherwise a new tag (LI > A) wouldn't have this event attached to it.
$(e.target).parent().remove();
}
else {
// Sets the focus() to the input field, if the user clicks anywhere inside the UL.
// This is needed because the input field needs to be of a small size.
tag_input.focus();
}
});
tag_input.keydown(function(event) {
if (event.which == BACKSPACE) {
if (tag_input.val() == "") {
// When backspace is pressed, the last tag is deleted.
tags.pop();
$(el).children(".tagit-choice:last").remove();
}
}
// Comma/Space/Enter are all valid delimiters for new tags.
else if (event.which == COMMA || (event.which == SPACE && !options.allowSpace) || event.which == ENTER) {
event.preventDefault();
var typed = tag_input.val();
typed = typed.replace(/,+$/, "");
typed = typed.trim();
if (typed != "") {
if (is_new(typed)) {
create_choice(typed);
}
// Cleaning the input.
tag_input.val("");
}
}
});
tag_input.autocomplete({
source: options.availableTags,
select: function(event, ui) {
if (is_new(ui.item.value)) {
create_choice(ui.item.value);
}
// Cleaning the input.
tag_input.val("");
// Preventing the tag input to be update with the chosen value.
return false;
}
});
function is_new(value) {
if (value in oc(tags))
return false;
return true;
}
function create_choice(value) {
var el = "";
el = "<li class=\"tagit-choice\">\n";
el += value + "\n";
el += "<a class=\"tagit-close\">x</a>\n";
el += "<input type=\"hidden\" style=\"display:none;\" value=\"" + value + "\" name=\"item[tags][]\">\n";
el += "</li>\n";
var li_search_tags = this.tag_input.parent();
$(el).insertBefore(li_search_tags);
this.tag_input.val("");
tags.push(value);
}
function oc(a) {
var o = {};
for (var i = 0; i < a.length; i++) {
o[a[i]] = '';
}
return o;
}
};
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
})(jQuery);
,我會怎麼稱呼呢? – Hailwood 2011-02-03 03:32:53