简体   繁体   English

使用HTML标签对数组进行排序

[英]Sorting an array with HTML tags

I have an array being generated in this format called statecontent : 我有一个以这种格式生成的数组,称为statecontent

["<option value="Texas" data-code="TX">Texas - TX</option>", 
"<option value="Washington" data-code="WA">Washington - WA</option>", 
"<option value="Maryland" data-code="MD">Maryland - MD</option>""]

I'm using this array to populate a drop down box 我正在使用此数组填充下拉框

var statecombo = $('#stateCombobox');    
statecombo.append(statecontent.join(''))

However none of the normal sorting methods I'm using are working. 但是,我使用的所有普通排序方法都无法正常工作。

Usually I would do: 通常我会这样做:

var target = '#stateCombobox'
sortdropdown(target) 

 function sortdropdown(target) {
         $(target).html($(target + " option").sort(function (a, b) {
                 return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;
         }));
 }

This doesnt work though, any idea how I could sort with this kind of format? 但是,这不起作用,我知道如何使用这种格式进行排序吗?

Tried this and this with no success I guess because they are in html tags? 我尝试过这个没有成功,因为它们在html标记中?

Not sure how sorting before appending would work, as i generate it like: 不知道附加之前如何排序,因为我生成它像:

for (var j = 0; j < obj[k].countries[i].states.length; j++) {                                                     
             var item = '<option value="' + obj[k].countries[i].states[j].state + '" data-code="' + Scode + '">' + obj[k].countries[i].states[j].state;
             item = item + '</option>';
             statecontent.push(item);
     };

You can sort the elements before adding them to the DOM and then add them; 您可以先对元素进行排序,然后再将其添加到DOM中,然后再添加它们。 that should work. 那应该工作。

var statecontent = ['<option value="Texas" data-code="TX">Texas - TX</option>', 
'<option value="Washington" data-code="WA">Washington - WA</option>', 
'<option value="Maryland" data-code="MD">Maryland - MD</option>'];

statecontent.sort(function(a,b) {
    return $(a)[0].text == $(b)[0].text ? 0 : $(a)[0].text < $(b)[0].text ? -1 : 1;
});            

And you also need to use single quotes for your array elements as you are already using the double quotes for the attributes, or at least escape it in the attributes. 而且,您还需要对数组元素使用单引号,因为您已经在属性中使用了双引号,或者至少在属性中将其转义了。

WORKING JSFIDDLE DEMO 工作JSFIDDLE演示

Most of the time, when you find yourself having to query the DOM or HTML strings for data, it's a good indicator that there's something wrong in the design. 大多数时候,当您发现必须查询DOM或HTML字符串以获取数据时,它可以很好地表明设计中存在问题。 Always try to have a clean seperation between data and your presentation's code. 始终尝试将数据与演示文稿的代码区分开来。

Simple exemple: http://jsfiddle.net/43NED/2/ 简单示例: http : //jsfiddle.net/43NED/2/

!function () {
    var states = [
        { name: "Texas", code: "TX" },
        { name: "Washington", code: "WA" },
        { name: "Maryland", code: "MD" }
    ];

    populateStates(sortBy(states, 'name'));


    function populateStates(states) {
        var optionsFrag = document.createDocumentFragment();

        states.forEach(function (state) {
            optionsFrag.appendChild(new Option(state.name, state.code));
        });

        $('#stateCombobox').append(optionsFrag);
    }

    function sortBy(states, key) {
        return states.sort(function (a, b) {
            return a[key] < b[key]? -1 : +(a[key] > b[key]);
        });
    }
}();
var tags = ['<option value="Texas" data-code="TX">Texas - TX</option>', 
'<option value="Washington" data-code="WA">Washington - WA</option>', 
'<option value="Maryland" data-code="MD">Maryland - MD</option>'];

var pattern = new RegExp("<[^>]*>", "g");

tags.sort(function (a, b) {
    return a.replace(pattern,"") > b.replace(pattern, "") ? 1 : -1 ;
});

var s = $('#s');
s.append(tags.join());

I like the other answer because it doesnt strip out HTML to compare, but you need them as html elements for that to work. 我喜欢其他答案,因为它不会去除HTML进行比较,但是您需要将它们作为html元素才能正常工作。

Or you can detach the 'option' elements, do the sort then reappend to the 'select' element: 或者,您可以分离'option'元素,进行排序,然后重新添加到'select'元素:

$(target + ' option').detach().sort(function (a, b) {
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;
}).appendTo(target);

Demo (jsfiddle) 演示(jsfiddle)

but sorting the original array before building the dom elements is cleaner: 但是在构建dom元素之前对原始数组进行排序更干净:

// sort states
var sortedStates = obj[k].countries[i].states.sort();

for (var j = 0; j < sortedStates.length; j++) {
    var item = '<option value="' + sortedStates[j].state 
                + '" data-code="' + Scode + '">' + sortedStates[j].state;
    item = item + '</option>';
    statecontent.push(item);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM