模組化封裝,相容seajs
/** * User: c3t * Date: 14-3-25 * Time: 下午4:16 */ define(function (require, exports, module) { return function (jQuery) { (function ($) { var setting = null; $.fn.keywordInput = function (opts) { setting = $.extend({ number: 5, //關鍵字數量限定 msg: "請輸入關鍵字,通過逗號或者回車確認" }, opts || {}); init(this); this.keyup(inputKeywords); //通過事件委派。對新加入的標籤新增事件 $("#keywords-wrap").on("click", ".keyword-shut", function (event) { $(this).parent(".keyword-in").remove(); event.preventDefault(); }); }; function init(input) { $(input).val(setting.msg); $(input).addClass("keyword-input"); $(input).wrap("<div id='keyword-container'></div>").before("<div id='keywords-wrap'></div>"); $(input).focus(function () { $(this).val(""); }); $(input).blur(function () { $(this).val(setting.msg); }); } function inputKeywords(event) { var code = event.keyCode; if (code == 188 || code == 13) { var c = $(this).val(); if(c!="") { if($(".keyword-in").length >=setting.number){ alert("最多隻能允許新增"+setting.number+"個關鍵字"); event.preventDefault(); return false; } //防止關鍵字重複 var aks = $("input[name='aks']"); for(var i=0;i<aks.length;i++) { if($(aks[i]).val()==c) { alert("不能新增重複的關鍵字"); event.preventDefault(); return false; } } var ki = createKeyWord(c); $('#keywords-wrap').append(ki); $(this).val(""); } } } function createKeyWord(val) { return "<div class='keyword-in'>"+ "<span>"+val+"</span>"+ "<a href='#' class='keyword-shut'>×</a>"+ "<input type='hidden' name='aks' value='"+val+"'/>"+ "</div>"; } })(jQuery); } });
css 樣式
#keyword-container { border: 1px solid #bbb; width: 300px; } input.keyword-input { border: none; width: 300px; color: #aaa; height: 28px; } .keyword-in { float: left; font-size: 12px; margin: 3px; background: #3fa7cb; color: #fff; } .keyword-shut:link, .keyword-shut:visited { color: #fff; text-decoration: none; } a.keyword-shut:hover { color: #ff0000; }
頁面
<input type="text" id="keyword-input" value=""/>
呼叫
$("#keyword-input").keywordInput();