一、需求
最近客戶需要將他們的房屋系統標籤做成點選方式的,於是自己就簡單整理了下;
二、用到類庫和函數
jquery
$(this).toggleClass(特換CSS樣式) //用來切換CSS類樣式
$.inArray(要查找的字符串,數組集) //jquery在數組中查找是否存在相應內容 返回-1未找到 或者返回數組下標,從0開始
$('DOM元素').each(function(k,v){ }); //遍歷DOM元素 k爲元素個數 v爲DOM元素
$.each(數組集,function(k,v){ }); //遍歷數組集 k爲鍵 v爲值
三、實現方式
1、(簡陋方式)通過給每個點擊的標籤增加class="on"樣式,然後遍歷樣式獲取點選內容
HTML代碼段:
<div id="mybt">
<input type="text" id="bt" name="bt" style="width:500px" /><br><br>
<span>精裝修家</span> <span>電齊全</span> <span>押一付一</span> <span>單身公寓</span> <span>鄰近地鐵</span> <span>市政供暖</span>
</div>
CSS代碼段:
<style type="text/css">
#mybt span{display:inline-block;width:4em;padding:5px 8px;margin:3px;border:1px solid #ccc;cursor:pointer}
.on{display:inline-block;width:4em;padding:5px 8px;margin:3px;border:1px solid #ccc;cursor:pointer;background-color:#6FD4F8;}
</style>
JS代碼段(引入jquery類):
<script type="text/javascript">
//選擇標籤
$(function(){
//每次點擊標題在數字中增加或者刪除一個標籤
$('#mybt span').click(function(){
//獲取點擊的當前標籤內容
var s = $(this).html();
//切換點擊樣式
$(this).toggleClass('on');
//清理文本框
$('#bt').val('');
//遍歷當前被選擇的標籤
var str = '';
$('#mybt span.on').each(function(k,v){
str += $(v).html()+',';
//$('#bt').val($(v).html()+',');
});
//顯示到文本框
$('#bt').val(str);
});
});
</script>
=========================================================
2、(推薦方式)通過點擊將選擇的標籤存入數組中,然後對其進行增加刪除,最後將數組的內容輸出到顯示的文本框中及爲最終點選的內容
HTML代碼段:
<body>
<div id="mybt">
<input type="text" id="bt" name="bt" style="width:500px" /><br><br>
<span>精裝修家</span> <span>電齊全</span> <span>押一付一</span> <span>單身公寓</span> <span>鄰近地鐵</span> <span>市政供暖</span>
</div>
CSS代碼段:
<style type="text/css">
#mybt span{display:inline-block;width:4em;padding:5px 8px;margin:3px;border:1px solid #ccc;cursor:pointer}
.on{display:inline-block;width:4em;padding:5px 8px;margin:3px;border:1px solid #ccc;cursor:pointer;background-color:#6FD4F8;}
</style>
JS代碼段(引入JQUERY類):
<script type="text/javascript">
//選擇標籤
$(function(){
//定義一個從來存儲標籤的數組
var arrStr = new Array();
//每次點擊標題在數字中增加或者刪除一個標籤
$('#mybt span').click(function(){
var t = $('#bt').val(); //獲取text中已經存的標籤內容
var s = $(this).html(); //獲取點擊的當前標籤內容
//如果當前點擊的標籤存在於標籤數組數組中就刪除 不存在就新增(目的點擊增加刪除切換)
var num = $.inArray(s,arrStr); /* $.inArray(要查找的字符串,數組集) jquery數組查找函數 */
//如果$.inArray()返回負數表示數組中不存在,否則返回字符串存在於數組中的下標 0開始
if(num>'-1'){
//點擊去色
$(this).removeClass("on");
//剔除標籤
arrStr.splice(num,1);
}else{
//點擊上色
$(this).addClass("on");
//數組中追加標籤
arrStr.push(s);
}
//每次點擊情況標籤顯示框
$('#bt').val('');
//遍歷出來標籤數組 jquery遍歷數組 $.each(數組集,function(k,v){……});
$.each(arrStr,function(k,v){
//獲取原來的標籤數據
var oldData = $('#bt').val() + v;
//爲標籤添加分割符號
if(k != arrStr.length-1) oldData += ',';
//將最終數據遍歷到顯示框中
$('#bt').val(oldData);
});
});
});
</script>
源碼下載:
http://pan.baidu.com/s/1i3mp92l