通过javascript/jquery基于文本对dom中的元素进行排序

通过javascript/jquery基于文本对dom中的元素进行排序,javascript,jquery,Javascript,Jquery,以下是我的html结构: <div class="qotd"> <div class="inner"> <p id="19001"><span>text1</span> <br> <span class="uptext">1</span> <img

以下是我的html结构:

<div class="qotd">
    <div class="inner">
                <p id="19001"><span>text1</span>

                  <br>
                  <span class="uptext">1</span>
                  <img class="im upimg" src="http://www.deratus.com/pictures/2010/02/Up-championed-to-win-oscar.jpg">
                  <img class="im downimg" src="http://www.freeclipartnow.com/d/40224-1/arrow-blue-rounded-down.jpg">
                  <span class="downtext">2</span>
                </p>
            </div>
</div>
我编写了以下jquery,根据段落的上下票数对段落进行排序:

$(function){
$("#pos").click(function(e) {
    console.log("up");
        e.preventDefault();
        $('.inner').sort(function(a, b) {

            return parseInt($('.uptext', b).text(), 10) - parseInt($('.uptext', a).text(), 10) ;
        }).appendTo('div.qotd');
    });

    $("#neg").click(function(e) {
      console.log("down");
        e.preventDefault();
        $('.inner').sort(function(a, b) {
            return parseInt($('downtext', b).text(), 10) - parseInt($('.downtext', a).text(), 10);
        }).appendTo('div.qotd');
    });
}
JSFIDLE是
尽管存在上述所有问题,但我没有得到正确的结果,哪里出了问题?

您的
$(function(){
.ready handler)和一个
.downtext
选择器中有一个输入错误。我将排序算法稍微修改为

return +$(b).find('.uptext').text() - +$(a).find('.uptext').text();


这仍然是一个有点可疑的操作。每次调用这些排序函数+jQuery开销时,您都在执行大量查询/DOM爬网。

您得到的结果是什么,是按错误的顺序排序,还是抛出了错误?更新了小提琴,请检查它。@user902620您的JSFIDLE抛出了一个错误,使它停止运行。C检查开发人员控制台以查看错误。更新了编辑的链接。
$('downtext',b).text()
应该是
$('.downtext',b).text()
…然后它就可以工作了。请您解释一下-+的事情,我不明白,这种排序和选择器实际上是如何工作的。使用它有什么问题:返回parseInt($('.uptext',b).text(),10)-parseInt($('.uptext',a).text(),10);@user902620:请参阅。这只是一种较短的书写方式。
$(a,b)
调用
$(b)。在内部查找(a)
,因此通常更倾向于直接使用此表单。@user902620:使用
parseInt()没有任何错误
,但对于您来说,它有点冗长和缓慢。
+
将在数字版本中“强制”一个字符串(如果我们处理的是数字),否则它将返回
NaN
return +$(b).find('.uptext').text() - +$(a).find('.uptext').text();