问题
I need to build a list with 6 li
's and their values (empty or not) and then append it to an existing li
.
Having these results in return from an sql query:
id_news title category order
------- -------- -------- -----
3 Alex... 12 1
12415 Obama... 3 3
With that data I need to build an in order by order
list, and by that I mean that the list should be something like:
<ul>
<li data-order="1"> Alex... </li>
<li data-order="2"> No featured news here, click to add </li>
<li data-order="3"> Obama... </li>
<li data-order="4"> No featured news here, click to add </li>
<li data-order="5"> No featured news here, click to add </li>
<li data-order="6"> No featured news here, click to add </li>
</ul>
So, my questions are:
- Should I have a predefined list and add data there?
- Or, should I do it while building the list? If so, how?
The jQuery code that I have by now:
var sublist = '<ul id="order_list"> <h3> Order list: </h3>';
$.each(data, function(index, value) {
sublist += '<li data-target="'+value['id_news']+'">'+value['headline']+'</li>';
});
sublist += '</ul>';
list.append(sublist);
回答1:
The important thing is to remember to just get all the markup string text the way you want it before inserting into the DOM, that's going to be 99% of the optimization (not that you aren't, just pointing out that that's definitely the focus to keep).
As for accomplishing that: use the same code you have for creating the markup, but sort your "data" array first. Use javascript arrays' "sort" function for that. This jsfiddle shows it happening.
var data = [{order:5}, {order:45}, {order:4}, {order:200}];
data.sort(function(a,b){return a.order-b.order;});
$.each(data,function(index, value){
document.write(value.order+'<br/>');
});
// output shows the array ordered by the val of the objects' order prop
I'm assuming that your data array holds objects with an order property that is numeric. Of course, if the property is named something else then change accordingly, and if it's a string instead of numeric, then use Number() within the function in order for the math to work.
来源:https://stackoverflow.com/questions/10619016/jquery-append-data-to-html-according-to-order-number