首頁 > web前端 > js教程 > 主體

jQuery如何選擇性移除列錶框

coldplay.xixi
發布: 2023-01-04 09:36:31
原創
1915 人瀏覽過

jQuery選擇性移除列錶框的方法:綁定向左的方向建按鈕的click事件,當按一下按鈕時,右側列錶框選取的項目會加入到左側列錶框中,完成移除的操作,程式碼為【$(this).remove().appendTo(leftSel)】。

jQuery如何選擇性移除列錶框

本教學操作環境:windows7系統、jquery3.2.1版本,Dell G3電腦。

jQuery選擇性移除列錶框的方法:

本文將以實例來講解使用jQuery實現左右列錶框的操作,主要有以下效果:

1、透過左右按鈕在右側列錶框中新增項目或移除項目操作。

2、透過雙擊兩邊列錶框裡的項目可以進行新增或移除項目。

3、取得右側列錶框裡的選項值。

<div class="select_side"> 
   <p>待选区</p> 
   <select id="selectL" name="selectL" multiple="multiple"> 
      <option value="13800138000">王新安 - 13800138000</option> 
      <option value="13800138001">李密 - 13800138001</option> 
      <option value="13800138002">姜瑜 - 13800138002</option> 
      <option value="13800138002">钱书记 - 13800138004</option> 
   </select> 
</div> 
<div class="select_opt"> 
   <p id="toright" title="添加">></p> 
   <p id="toleft" title="移除"><</p> 
</div> 
<div class="select_side"> 
   <p>已选区</p> 
   <select id="selectR" name="selectR" multiple="multiple"> 
   </select> 
</div> 
<div class="sub_btn"><input type="button" id="sub" value="getValue" /></div>
登入後複製

頁面由左右兩個列錶框以及操作按鈕項目組成。透過CSS來控制三者並排一行。

CSS

.select_side{float:left; width:200px} 
select{width:180px; height:120px} 
.select_opt{float:left; width:40px; height:100%; margin-top:36px} 
.select_opt p{width:26px; height:26px; margin-top:6px; background:url(arr.gif) no-repeat; 
 cursor:pointer; text-indent:-999em} 
.select_opt p#toright{background-position:2px 0} 
.select_opt p#toleft{background-position:2px -22px}
登入後複製

我設定了兩個列錶框都左浮動float:left,同時將操作按鈕項目也左浮動,主要就使得三者橫向排列。值得注意是,在設定操作按鈕時,我使用了一張背景圖片,這張圖片包括了左右兩個方向箭頭的按鈕,如下圖,然後透過background-position來定位圖片的位置,這個方法目前已經在許多網站中應用。

jQuery如何選擇性移除列錶框

jQuery

首先,綁定向右的方向建立按鈕的click事件,當按一下按鈕時,左側列錶框選取的項目會新增到右側列錶框中,完成新增的操作。

var leftSel = $("#selectL"); 
var rightSel = $("#selectR"); 
$("#toright").bind("click",function(){       
    leftSel.find("option:selected").each(function(){ 
        $(this).remove().appendTo(rightSel); 
    }); 
});
登入後複製

同樣,綁定向左的方向建立按鈕的click事件,當單擊按鈕時,右側列錶框選中的項目會添加到左側列錶框中,完成移除的操作。

$("#toleft").bind("click",function(){        
    rightSel.find("option:selected").each(function(){ 
        $(this).remove().appendTo(leftSel); 
    }); 
});
登入後複製

接下來,需要完成雙擊選擇事件,當雙擊該項目時,該項目立即從該列錶框中移除,並添加到與之相對的列錶框中。

leftSel.dblclick(function(){ 
    $(this).find("option:selected").each(function(){ 
        $(this).remove().appendTo(rightSel); 
    }); 
}); 
rightSel.dblclick(function(){ 
    $(this).find("option:selected").each(function(){ 
        $(this).remove().appendTo(leftSel); 
    }); 
});
登入後複製

以上程式碼有點多,但是非常直觀,而且非常容易理解,有了這些操作後,就能對列錶框的值進行隨心所欲的控制了。

相關免費學習推薦:javascript(影片)

#########

以上是jQuery如何選擇性移除列錶框的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!