这在参数方面是如何工作的(我在对选择框进行排序时使用它):
$(this).html( $("option", $(this)).sort( function(a, b) {return a.text == b.text ? 0 : a.text < b.text ? -1 : 1}));
如果 $(this)
表示“选择”菜单,则参数是排序的“选项”值的集合。还是有更好/更清晰的方式来解释正在发生的事情?
最佳答案
您要求解释,这里是简单的英文解释:
For this
<select>
element, take the existing<option>
, put them into an array, and sort them by their text value, then replace the existing html with the new sorted options.
代码的等效 jQuery,带有变量名以帮助您了解正在发生的事情:
var currentOptions = $("option", $(this));
var sortedOptions = currentOptions.sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
});
$(this).html(sortedOptions);
发生的排序是一种 JavaScript 方法,请在此处阅读:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
关于javascript - jQuery .html() 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8303686/