是否可以将列表从较低的数字排序到较大的数字,保留每个li的内容?
<ul>
<li>
39
<img class="botao-remover-tamanho" title="Remover cor" alt="" src="/admin/imagens/botao-excluir-cor.png">
<input type="hidden" title="39" value="39" name="array_variacao[]">
</li>
<li>
34
<img class="botao-remover-tamanho" title="Remover cor" alt="" src="/admin/imagens/botao-excluir-cor.png">
<input type="hidden" title="34" value="34" name="array_variacao[]">
</li>
<li>
38
<img class="botao-remover-tamanho" title="Remover cor" alt="" src="/admin/imagens/botao-excluir-cor.png">
<input type="hidden" title="38" value="38" name="array_variacao[]">
</li>
<li>
35
<img class="botao-remover-tamanho" title="Remover cor" alt="" src="/admin/imagens/botao-excluir-cor.png">
<input type="hidden" title="35" value="35" name="array_variacao[]">
</li>
<li>
33
<img class="botao-remover-tamanho" title="Remover cor" alt="" src="/admin/imagens/botao-excluir-cor.png">
<input type="hidden" title="33" value="33" name="array_variacao[]">
</li>
</ul>
我需要它自动命令,因为列表将动态创建。
<ul>
<li>
33
<img class="botao-remover-tamanho" title="Remover cor" alt="" src="/admin/imagens/botao-excluir-cor.png">
<input type="hidden" title="33" value="33" name="array_variacao[]">
</li>
<li>
34
<img class="botao-remover-tamanho" title="Remover cor" alt="" src="/admin/imagens/botao-excluir-cor.png">
<input type="hidden" title="34" value="34" name="array_variacao[]">
</li>
<li>
35
<img class="botao-remover-tamanho" title="Remover cor" alt="" src="/admin/imagens/botao-excluir-cor.png">
<input type="hidden" title="35" value="35" name="array_variacao[]">
</li>
<li>
38
<img class="botao-remover-tamanho" title="Remover cor" alt="" src="/admin/imagens/botao-excluir-cor.png">
<input type="hidden" title="38" value="38" name="array_variacao[]">
</li>
<li>
39
<img class="botao-remover-tamanho" title="Remover cor" alt="" src="/admin/imagens/botao-excluir-cor.png">
<input type="hidden" title="39" value="39" name="array_variacao[]">
</li>
</ul>
感谢您的帮助!
修改
通过评论中的@Blender建议,我在下面的帖子中使用了代码,它对我来说很好。
答案 0 :(得分:3)
尝试以下代码,
$(function() {
$('button').click(function() {
var liContents = [];
$('ul li').each(function() {
liContents.push($(this).html());
});
liContents.sort(liSorter);
$('ul li').each(function() {
$(this).html(liContents.pop());
});
});
});
/*
Below function is kind of a workaround for the listed HTMl
you need to update it if you have proper HTML.
*/
function liSorter(a, b) {
return (parseInt(b) - parseInt(a));
}
编辑:稍微更新了您的标记,以获得更好的代码,
span
<span class="num">39</span>
标记包裹这些号码
<强>代码:强>
function numOrdDesc(a, b) {
var aTxt = parseInt($(a).find('.num').text(), 10);
var bTxt = parseInt($(b).find('.num').text(), 10);
return (bTxt - aTxt);
}
答案 1 :(得分:0)
你的功能应该是这样的。
function numOrdDesc(a, b) {
var aTxt = parseInt($(a)[0].innerText, 10);
var bTxt = parseInt($(b)[0].innerText, 10);
return (bTxt - aTxt);
}