如何根据特定div中的文本对DOM元素进行排序?

时间:2016-09-07 20:23:58

标签: javascript jquery html

我正在尝试使用jQuery和JS创建一个简单的reddit克隆。我创建了一个表单,用户可以通过表单提交“帖子”的标题和内容。此外,每个帖子都附带一个互动的小投票div。

我已经将前三个帖子硬编码到HTML中(如下所示)。

<div class="panel panel-default" id="formStuff">
          <div class="form-group">
            <label for="title">Title </label> </label>
            <input type="title"  id="title" class="form-control">
          </div>
          <div class="form-group">
            <label for="content">Content </label>
            <textArea rows="5" type="content" id="content" class="form-control"></textArea>
          </div>
          <input type="submit" class="btn btn-success" id="subbtn">
     </div>

    <div class="wrapper">
        <div class="panel panel-default">
          <div class="vote">
            <p class='button plus'><i class="fa fa-arrow-up" aria-hidden="true"></i></p><p class='count'>0</p><p class='button minus'><i class="fa fa-arrow-down" aria-hidden="true"></i>
            </p>
          </div>
          <div class="pic">
              <img src="https://upload.wikimedia.org/wikipedia/en/8/84/AtlasShrugged.jpg">
          </div>
          <h3 id="aShrugged">Atlas Shrugged</h3>
          <p>Ayn Rand's objectivism adopted by US president Donald Trump. A crusade of eugenics begins anew.</p>
        </div>  
    </div>
    <div class="wrapper">
        <div class="panel panel-default">
          <div class="vote">
            <p class='button plus'><i class="fa fa-arrow-up" aria-hidden="true"></i></p><p class='count'>0</p><p class='button minus'><i class='fa fa-arrow-down' aria-hidden='true'></i>
            </p>
          </div>
          <div class='pic'>
              <img src='https://upload.wikimedia.org/wikipedia/en/8/84/AtlasShrugged.jpg'>
          </div>
          <h3 id="aShrugged">Atlas Shrugged</h3>
          <p>Ayn Rand's objectivism adopted by US president Donald Trump. A crusade of eugenics begins anew.</p>
        </div>  
    </div>
   <div class="wrapper">
        <div class="panel panel-default">
          <div class="vote">
            <p class='button plus'><i class="fa fa-arrow-up" aria-hidden="true"></i></p><p class='count'>0</p><p class='button minus'><i class="fa fa-arrow-down" aria-hidden="true"></i>
            </p>
          </div>
          <div class="pic">
              <img src="https://upload.wikimedia.org/wikipedia/en/8/84/AtlasShrugged.jpg">
          </div>
          <h3 id="aShrugged">Atlas Shrugged</h3>
          <p>Ayn Rand's objectivism adopted by US president Donald Trump. A crusade of eugenics begins anew.</p>
        </div>  
    </div>

由于我想根据投票数(从最高到最低)动态排列div,我该怎么做?目前,我正在尝试实施线性搜索,搜索最高数字并对其进行排序。不过,我认为必须有一个更简单的方法..任何帮助或想法都赞赏:)

我的代码/伪代码:(线性搜索具有最高票数的div,然后通过交换div将其移动到必要的位置)

for (var j = 0; j < ($(".wrapper").length - 1); j++) {

  var largestNum = Number($(".count")[j].childNodes[0].nodeValue);
  var content2 = $(".wrapper").eq(j).html();
  var content2 = $(
  for (var i = 0; i < ($(".wrapper").length - 1); i++)
  {
      if largestNum >= Number($(".count")[j + 1].childNodes[0].nodeValue)
          largestNum  stays the same
      else if largestNum < Number($(".count")[j +     
            1].childNodes[0].nodeValue)
          largestNum = Number($(".count")[j + 1].childNodes[0].nodeValue);
  }

  if ( largestNum === Number($(".count")[j].childNodes[0].nodeValue) ) { if    
the first count is largest, keep it in its current spot}
  else {
      var content1 = $(".wrapper").eq(j).html();
      var content2 = largestNum.eq(j).html();  //the wrapper where this count is located
    //find which div corresponds to the count number
     //$(".count:first").parents().eq(2).html() - gives html of parents two levels up
    $(".wrapper").eq(j).html(content2);
    largestNum(content1)    
}

}   

1 个答案:

答案 0 :(得分:2)

据推测,您的实际页面将是动态的,并从某种数据库中提取数据。老实说,在生成html输出之前,您可以更好地对数据集本身进行排序。如何执行此操作取决于您在

中存储数据的方式和检索数据的格式

那就是说,如果你真的想在DOM中这样做,(比如在投票后重新排序),你可以使用.sort()函数,如下所示。请注意,为了更轻松地完成这项工作,我添加了<div class="wrapper-group">作为包装器div的包装器:

function sortWrappers() { // function to sort the DOM
  var $wrapperGroup = $('.wrapper-group'),
    $wrappers = $wrapperGroup.find('.wrapper');

  $wrappers.sort(function(a, b) {
    var an = Number($(a).find('.count').text());
    var bn = Number($(b).find('.count').text());
    if (an > bn) return -1;
    if (an < bn) return 1;
    return 0;
  });

  $wrappers.detach().appendTo($wrapperGroup);
}

$(function() { // wait till dom loads to add handler

  $(document).on('click', '.vote .button', function() { // handler to add or subtract votes ans call funtion to re-sort
    var $this = $(this);
    var $countDiv = $this.closest('.vote').find('.count');
    var count = Number($countDiv.text());
    var shouldAdd = $this.hasClass('plus');
    count = shouldAdd ? count + 1 : count - 1; // add or subtract based on button pushed
    $countDiv.text(count);
    sortWrappers();
  });

  sortWrappers(); // call function here to sort divs once on page load
});
.vote .button {
  cursor: pointer;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-default" id="formStuff">
  <div class="form-group">
    <label for="title">Title</label>
    <input type="title" id="title" class="form-control">
  </div>
  <div class="form-group">
    <label for="content">Content</label>
    <textArea rows="1" type="content" id="content" class="form-control"></textArea>
  </div>
  <input type="submit" class="btn btn-success" id="subbtn">
</div>

<div class="wrapper-group">

  <div class="wrapper">
    <div class="panel panel-default">
      <div class="vote">
        <p class='button plus'><i class="fa fa-arrow-up" aria-hidden="true"></i>
        </p>
        <p class='count'>2</p>
        <p class='button minus'><i class="fa fa-arrow-down" aria-hidden="true"></i>
        </p>
      </div>
      <div class="pic">
        <img src="https://upload.wikimedia.org/wikipedia/en/8/84/AtlasShrugged.jpg">
      </div>
      <h3 id="aShrugged">Atlas Shrugged</h3>
      <p>Ayn Rand's objectivism adopted by US president Donald Trump. A crusade of eugenics begins anew.</p>
    </div>
  </div>

  <div class="wrapper">
    <div class="panel panel-default">
      <div class="vote">
        <p class='button plus'><i class="fa fa-arrow-up" aria-hidden="true"></i>
        </p>
        <p class='count'>3</p>
        <p class='button minus'><i class='fa fa-arrow-down' aria-hidden='true'></i>
        </p>
      </div>
      <div class='pic'>
        <img src='https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQ8n3ycTsYghXZls7NdBULWq0xqE4OW5G_cdYvNG4hcEAZVdCyHuQ'>
      </div>
      <h3 id="aShrugged">Atlas Shrugged</h3>
      <p>Ayn Rand's objectivism adopted by US president Donald Trump. A crusade of eugenics begins anew.</p>
    </div>
  </div>

  <div class="wrapper">
    <div class="panel panel-default">
      <div class="vote">
        <p class='button plus'><i class="fa fa-arrow-up" aria-hidden="true"></i>
        </p>
        <p class='count'>5</p>
        <p class='button minus'><i class="fa fa-arrow-down" aria-hidden="true"></i>
        </p>
      </div>
      <div class="pic">
        <img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTjGUgGlwA_F-fmbMqrUbHcZMKHuGLPi3DP8mZH5fLOCQZjfyTKTQ">
      </div>
      <h3 id="aShrugged">Atlas Shrugged</h3>
      <p>Ayn Rand's objectivism adopted by US president Donald Trump. A crusade of eugenics begins anew.</p>
    </div>
  </div>

</div>