我使用JQuery填充SELECT元素,以减少输出标记的大小。
一切都按我想要的方式工作,只有一件事例外:排序。
看起来,当我在下面的代码中找到.each时,JQuery是按val值而不是text值排序的。我希望列表按text值排序,或者更理想的情况是,按照在变量dyn_list_product中生成列表的顺序排序。
我如何才能做到这一点呢?
非常感谢。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Sample Code</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type = "text/javascript" >
$(document).ready(function(){
var dyn_list_product = { 10075:'abc', 10635:'def', 10246:'ghi', 10245:'jkl', 10076:'mno', 10642:'pqr', 10995:'stu', 10255:'vwx', 10230:'yz' };
$('.jquery_list_product').append( $('<option></option>').val('').html('----------') );
$.each( dyn_list_product , function(val, text) { $('.jquery_list_product').append( $('<option></option>').val(val).html(text) ); });
})
</script>
</head>
<body>
<select name="insert-1[]" class="jquery_list_product"></select>
<select name="insert-2[]" class="jquery_list_product"></select>
<select name="insert-3[]" class="jquery_list_product"></select>
</body>
</html>发布于 2013-01-01 06:25:13
jQuery代码没有对任何内容进行排序。在JavaScript中,对象键的迭代顺序是未定义的。也就是说,以某种顺序定义属性这一事实与.each()函数将它们传递给处理程序的顺序无关。
请改用数组:
var dyn_list_product = [ { key: '10075', val: 'abc'}, { key: '10635', val: :'def'}, ... ];然后,您的.each()循环将如下所示:
$.each( dyn_list_product , function(index, obj) {
$('.jquery_list_product').append( $('<option></option>').val(obj.key).html(obj.val) ); });
})https://stackoverflow.com/questions/14106507
复制相似问题