你是否用過那種可以不停新增關鍵字的標籤輸入框?本文示範如何以 jQuery 打造一個可動態添加標籤的輸入元件,並能一次取出所有已輸入的值。
效果體驗:
https://hovertree.com/texiao/jquery/67/
效果圖:
參考:
https://hovertree.com/h/bjaf/traversing_each.htm
標籤區由一個提示容器 .tip 構成,點擊後即可加入新的標籤欄位。頁面下方還提供一個「獲取全部值」的按鈕,方便一次收集所有標籤內容:
<div class="site">
<div class="title">標籤:</div>
<div class="tip">
<div class="tip-container"><span class="jia"></span>添加標籤</div>
</div>
</div>
<div class="hovertreeinfo">
<input type="button" value="獲取全部值" id="hovertreeall" />
<span id="hovertreeresult"></span>
</div>真正的技巧在於用 jQuery 的 each() 遍歷所有標籤欄位,將值逐一附加到結果區:
$("#hovertreeall").on("click", function () {
$("#hovertreeresult").html("<br />");
$(":input.house-tip").each(function () {
$("#hovertreeresult").append($(this).val()+"<br />");
});
});搭配外部的 tip.js 與 tip.css,就能完成新增與取值的完整流程,非常適合標籤、關鍵字或收件人欄位等場景。
<script src="https://down.hovertree.com/jquery/jquery-1.12.3.min.js"></script>
<script src="https://hovertree.com/texiao/jquery/67/js/tip.js"></script>