我有多个具有不同值的单选按钮。我想根据 value
或 id
按以下顺序对这些按钮进行排序:
- 联邦 express 地面
- UPS 地面
- 自定义 1
- 自定义 2
由于所有选项的类和名称都相同,因此值和 ID 不同。我尝试过使用 JavaScript,但除了使用升序、降序和随机排序之外,我无法弄清楚如何按值按自定义顺序对选项进行排序。
<ul id="shipping_method">
<li>
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_1" value="booster_custom_shipping_1" class="shipping_method" checked="checked">
<label for="shipping_method_custom_shipping_1">Custom 1:</label>
</li>
<li>
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_2" value="booster_custom_shipping_2" class="shipping_method">
<label for="shipping_method_custom_shipping_2">Custom 2:</label>
</li>
<li>
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_3" value="FedEx - FedEx Ground" class="shipping_method">
<label for="shipping_method_fedex_ground">FedEx Ground:</label>
</li>
<li>
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_4" value="UPS - UPS Ground" class="shipping_method">
<label for="shipping_method_ups-ground">UPS Ground:</label>
</li>
</ul>
最佳答案
创建一个排序对象,查找其中的值,并根据该值进行排序:
var ordering = {
"FedEx - FedEx Ground": 1,
"UPS - UPS Ground": 2,
"booster_custom_shipping_1": 3,
"booster_custom_shipping_2": 4
};
$('#shipping_method > li').
sort(
function(a, b) {
// for each <li>, get the value of the <input> it contains
// look up that value in `ordering`, and use that for comparison
//
return ordering[ $('input', a).val() ] - ordering[ $('input', b).val() ];
}
).
each(
// appending each element in sorted order leaves a sorted list behind
//
function() {
$('#shipping_method').append(this);
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="shipping_method">
<li>
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_1" value="booster_custom_shipping_1" class="shipping_method" checked="checked">
<label for="shipping_method_custom_shipping_1">Custom 1:</label>
</li>
<li>
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_2" value="booster_custom_shipping_2" class="shipping_method">
<label for="shipping_method_custom_shipping_2">Custom 2:</label>
</li>
<li>
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_3" value="FedEx - FedEx Ground" class="shipping_method">
<label for="shipping_method_fedex_ground">FedEx Ground:</label>
</li>
<li>
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_4" value="UPS - UPS Ground" class="shipping_method">
<label for="shipping_method_ups-ground">UPS Ground:</label>
</li>
</ul>
关于javascript - 按自定义顺序对输入值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44270313/