javascript - jQuery .html() 参数

标签 javascript jquery

这在参数方面是如何工作的(我在对选择框进行排序时使用它):

$(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/

相关文章:

javascript - 当变量未定义时执行某些操作

javascript - 如何切换 slider 上的复选框?

javascript - 如何在 javascript/jquery 中循环 json 并正确读取数据

javascript - HTML 和 JS : how to open website with viewport on mobile devices (iOS) with small viewport by default?

javascript - Jquery 数据表过滤器

javascript - 在fabricjs Canvas 上实现ClipTo功能

javascript - 使用javascript在表数据的基础上排列表行

javascript - 用于设计查询语言的正则表达式

javascript - Modal 中的两种方式绑定(bind)变量 - Angular

javascript - 在重新加载和加载时滚动到相同位置