1. 程式人生 > >jQuery Tags Input 外掛輸入框回車顯示標籤

jQuery Tags Input 外掛輸入框回車顯示標籤

效果

上來先引用檔案

<link rel="stylesheet" href="../css/jquery.tagsinput.css">
<script src="../js/jquery-1.10.2.min.js"></script>
<script src="../js/jquery.tagsinput.js"></script>

<input id="tags" type="text" class="tags" value="foo,bar,baz,roffle" />

簡單初始化

$('#tags').tagsInput();

你還可以使用addTag() and removeTag()函式增加和刪除掉標籤,如以下:

$('#tags').addTag('foo');
$('#tags').removeTag('bar');


你還可以用imporTags()方法導進一組tag列表,需要注意的是這樣會將value裡設定的預設tag替換掉

$('#tags').importTags('foo,bar,baz');

 

所以如果importTags()裡不帶值的話,就是重置input裡的標籤值(注意引號要保留,可以理解為給它傳空值。)

$('#tags').importTags('');

可以使用tagExist()判斷一個標籤是否存在:

if ($('#tags').tagExist('foo')) { ... }

如果想要在增加或移除掉標籤的時候增加額外的功能或觸發其它動作,你可以通過onAddTag和onRemoveTag這兩個引數裡指定回撥函。這兩個函式都返回了一個標籤值作為引數(原文: Both functions should accept a single tag as the parameter.)

$('#tags_1').tagsInput({
    width:'auto',
    onAddTag:function(tag){
    console.log('增加了'+tag)
},
onRemoveTag:function(tag){
        console.log('刪除了'+tag)
    }
});

API

$(selector).tagsInput({
   'autocomplete_url': url_to_autocomplete_api, //自動完成外掛的檔案地址,demo裡有說明
   'autocomplete': { option: value, option: value}, //自動完成外掛的引數,demo有說明.(提供個jquery.autocomplete的:
// http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/)
   'height':'100px', //設定高度
   'width':'300px',  //設定寬度
   'interactive':true, //是否允許新增標籤,false為阻止
   'defaultText':'add a tag', //預設文字
   'onAddTag':callback_function, //增加標籤的回撥函式
   'onRemoveTag':callback_function, //刪除標籤的回撥函式
   'onChange' : callback_function, //改變一個標籤時的回撥函式
   'removeWithBackspace' : true, //是否允許使用退格鍵刪除前面的標籤,false為阻止
   'minChars' : 0, //每個標籤的小最字元
   'maxChars' : 0 //每個標籤的最大字元,如果不設定或者為0,就是無限大
   'placeholderColor' : '#666666' //設定defaultText的顏色
});