我有这段代码:
<select id="edit-attributes-1" class="form-select required" name="attributes[1]">
<option selected="selected" value="">Please select</option>
<option value="62">2XL</option>
<option value="66">2XS</option>
<option value="63">3XL</option>
<option value="11">L</option>
<option value="10">M</option>
<option value="8">S</option>
<option value="14">XL</option>
<option value="12">XS</option>
</select>
如何按顺序重建? 括号中 - 值。因为它可以捕获。
3XS (63)
2XS (66)
XS (14)
S (8)
M (10)
L (11)
XL (14)
2XL (62)
3XL (63)
答案 0 :(得分:2)
您可以为您的选项提供订单属性:
<option value="62" order="8" >2XL</option>
<option value="66" order="1" >2XS</option>
<option value="63" order="9" >3XL</option>
...
然后使用this component对其进行排序:
$("select").find("option").sortElements(function(a, b){
var aIndex = parseInt(a.attr("order"));
var bIndex = parseInt(b.attr("order"));
return aIndex > bIndex;
});
答案 1 :(得分:2)
可以在不添加新属性的情况下以正确的顺序对选项元素进行排序,但最好让它们在服务器端排序。
/**
* Convert a size string to a numeric value.
*
* A size string is one of the letters S, M or L (small, medium or large)
* optionally preceded by an X, or a number and an X.
*
* This function will return NaN if the input is invalid and is not
* case-sensitive. The result may be zero or negative.
*/
function sizeValue(size) {
var sizes = { S: -1, M: 0, L: 1 },
value = sizes[size[size.length - 1].toUpperCase()];
if (typeof value == 'undefined') {
return NaN;
}
if (size.length > 2) {
// Assume strings of at least 3 characters match /\d+X[SML]/
value *= parseInt(size.substr(0, size.length - 2), 10) + 1;
}
else if (size.length > 1) {
// Assume two letter strings match /X[SML]/
value *= 2;
}
return value;
}
// Now use the sizeValue function to sort the option elements.
var options = $('#edit-attributes-1 option').get();
options.sort(function(a, b) {
// I'd prefer to use Node.textContent here, but this is compatible with
// elderly versions of IE.
a = $(a).text();
b = $(b).text();
return sizeValue(a) - sizeValue(b);
});
// Reinsert the option elements in the select in their new order.
$('#edit-attributes-1').append(options);
此处处于行动on jsFiddle。