jquery控制listbox中項的移動並排序的實現代碼

來源:互聯網
上載者:User

首先是html代碼,頁面上放2個listbox控制項和2個按鈕用於移動項目

複製代碼 代碼如下:<table border="0">
<tr>
<td width="156">全部水果:</td>
<td width="142"> </td>
<td width="482">我挑選的:</td>
</tr>
<tr>
<td rowspan="2"><asp:ListBox SelectionMode="Multiple" ID="listall" Rows="12" Width="156" runat="server"></asp:ListBox></td>
<td height="41" align="center">
<input type="button" id="btnleftmove" value=">>>" onclick="move('listall','listmy');"/><br /><br />
<input type="button" id="btnrighttmove" value="<<<" onclick="move('listmy','listall');"/>
</td>
<td rowspan="2"><asp:ListBox SelectionMode="Multiple" ID="listmy" Rows="12" Width="156" runat="server"></asp:ListBox></td>
</tr>
</table>

下面是在.cs檔案中綁定一些資料

複製代碼 代碼如下:public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
ArrayList list=DataArray();
for (int i = 0; i < list.Count; i++)
{
listall.Items.Add(list[i].ToString());
listall.Items[i].Attributes["tag"] = i.ToString(); //用tag記錄排序欄位
}
}
private ArrayList DataArray()
{
//用到的一些資料,這裡已預設按第一個字的拼音排序
ArrayList list = new ArrayList();
list.Add("草莓");
list.Add("梨");
list.Add("桔子");
list.Add("芒果");
list.Add("蘋果");
list.Add("香蕉");
return list;
}
}

在實際使用時可根據資料庫中的欄位排序
下面是jquery的代碼:

複製代碼 代碼如下://移動使用者選擇的角色
//setname:要移出資料的列表名稱 getname:要移入資料的列表名稱
function move(setname,getname)
{
var size=$("#"+setname+" option").size();
var selsize=$("#"+setname+" option:selected").size();
if(size>0&&selsize>0)
{
$.each($("#"+setname+" option:selected"), function(id,own){
var text=$(own).text();
var tag=$(own).attr("tag");
$("#"+getname).prepend("<option tag=\""+tag+"\">"+text+"</option>");
$(own).remove();
$("#"+setname+"").children("option:first").attr("selected",true);
});
}
//重新排序
$.each($("#"+getname+" option"), function(id,own){
orderrole(getname);
});
}
//按首字母排序角色列表
function orderrole(listname)
{
var size=$("#"+listname+" option").size();
var one=$("#"+listname+" option:first-child");
if(size>0)
{
var text=$(one).text();
var tag=parseInt($(one).attr("tag"));
//迴圈列表中第一項值下所有元素
$.each($(one).nextAll(), function(id,own){
var nextag=parseInt($(own).attr("tag"));
if(tag>nextag)
{
$(one).remove();
$(own).after("<option tag=\""+tag+"\">"+text+"</option>");
one=$(own).next();
}
});
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.