jQuery 根据数字对 DOM 进行排序

发布于 2025-01-03 00:50:54 字数 870 浏览 2 评论 0原文

以下是重复的类:

<div class="inner">
          <p> 
                    Text1 
                    <span class="plus"> 25</span>
                    <span class="minus">12</span>
          </p>
</div>



<div class="inner">
              <p> 
                        Text2 
                        <span class="plus"> 205</span>
                        <span class="minus">2</span>
              </p>
    </div>

我有两个 href 标签充当排序按钮:

<a href="#" id="pos">Sort by Positive.</a>
<a href="#" id="neg">Sort by Negative.</a>

通过 jQuery,如何重新渲染 dom,并根据按钮单击排序

小提琴位于此处

Following is the class which is repeated:

<div class="inner">
          <p> 
                    Text1 
                    <span class="plus"> 25</span>
                    <span class="minus">12</span>
          </p>
</div>



<div class="inner">
              <p> 
                        Text2 
                        <span class="plus"> 205</span>
                        <span class="minus">2</span>
              </p>
    </div>

I have two href tags to act as sort button:

<a href="#" id="pos">Sort by Positive.</a>
<a href="#" id="neg">Sort by Negative.</a>

Through jQuery, how can I re-render the dom, with the <p> sorted based on the button click?

The fiddle is located here.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

葵雨 2025-01-10 00:50:54

类似于:

$("#pos").click(function(e){
  e.preventDefault();

  $('.inner').sort(function (a, b) {
    return parseInt($('.plus', a).text(), 10) - parseInt($('.plus', b).text(), 10);
  })
  .appendTo('div.main');
});

$("#neg").click(function(e){
  e.preventDefault();

  $('.inner').sort(function (a, b) {
    return parseInt($('.minus', a).text(), 10) - parseInt($('.minus', b).text(), 10);
  })
  .appendTo('div.main');
});

http://jsfiddle.net/pHyDm/8/

虽然这两个函数基本上是相同并且可以/应该进行一些重构。

Something like:

$("#pos").click(function(e){
  e.preventDefault();

  $('.inner').sort(function (a, b) {
    return parseInt($('.plus', a).text(), 10) - parseInt($('.plus', b).text(), 10);
  })
  .appendTo('div.main');
});

$("#neg").click(function(e){
  e.preventDefault();

  $('.inner').sort(function (a, b) {
    return parseInt($('.minus', a).text(), 10) - parseInt($('.minus', b).text(), 10);
  })
  .appendTo('div.main');
});

http://jsfiddle.net/pHyDm/8/

Though the two functions are basically the same and could/should probably be refactored a bit.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文