[英]Sort <div> elements using jQuery
我的網站上有以下HTML代碼:
<div class="groups">
<div class="group">
Group 1 priority:
<select>
<option value="1.0">1</option>
<option value="2.0" selected="selected">2</option>
<option value="3.0">3</option>
</select>
</div>
<div class="group">
Group 2 priority:
<select>
<option value="1.0">1</option>
<option value="2.0">2</option>
<option value="3.0" selected="selected">3</option>
</select>
</div>
<div class="group">
Group 3 priority:
<select>
<option value="1.0" selected="selected">1</option>
<option value="2.0">2</option>
<option value="3.0">3</option>
</select>
</div>
</div>
我正在尋找一種方法來根據下拉列表中選擇的內容,使用jQuery對這些組在瀏覽器中顯示的順序進行排序。 當用戶在任何下拉列表中或頁面加載中選擇新值時,它應該求助。
這個問題最簡單的方法是什么?
我可以使用jQuery UI,如果可以以任何方式使用可排序的東西。 我無法找到使用它的方法。
更新 :<div class =“group”>中還有其他數據,無論它們在何處移動,都應遵循下拉列表。 組的數量從0到20不等。
編輯:這里有一些代碼可以做你想要的。 這里select_1
, select_2
等應該是下拉列表的ID。 getDropdown()
應該是一個函數,它使用您選擇的方法( document.getElementById().options.selectedIndex,
,,jquery等)返回給定下拉ID的選定值document.getElementById().options.selectedIndex,
<div id="parent">
<div id="child1">
..content
<select id="select_1">...content</select>
</div>
<div id="child2">
..content
<select id="select_2">...content</select>
</div>
<div id="child3">
..content
<select id="select_3">...content</select>
</div>
</div>
function sortValues()
{
/*Save the contents of each div in an array
so they can be looped through and
re inserted later*/
var content=[$("#child1").html(),$("#child2").html,$("#child3").html()];
//Get the value of all dropdowns and sort them
var sortedArray=[getDropdown("select_3"),getDropdown("select_2"),getDropdown("select_3")];
var sortedContent=new Array();
sortedArray.sort();
/*Loop through all the sorted values,
compare the value of each dropdown
against the sorted value and use that
to determine the new arrangement of the divs
*/
for (x=0; x< sortedArray.length; x++)
{
for (y=0; y<=content.length; y++)
{
if (getDropdown("dropdown_" + (y+1))==sortedArray[x])
{
sortedContent[x]=content[x];
//This will prevent the same div from being assigned again:
$("#select_" + (y+1)).remove();
break;
}
}
}
/* Empty the parent div so new divs can be inserted.
You can also do a fadeout/fadeIn of the div here
*/
$("#parent").empty();
for (x=0; x< sortedContent.length; x++)
{
$("#parent").append(sortedContent[x]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.