根据数据属性对子div排序 [英] Sort child div based on data attribute

查看:57
本文介绍了根据数据属性对子div排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试根据数据属性对子div进行排序

Trying to sort children div based on data attributes

下面的html代码是由CM生成的,可以按任何随机顺序检索数据.

The html code below is being generated by a CM and the data can be retrieved in any random order.

html代码是

<section class="box explore">
<div id="ProductContainer"  class="row">
        <div id="1232132" data-name="B" data-category="Category_A" class="explore-cell">
         <h>B</h>
         <p>Category_A</p>
        </div>
    <div id="123" data-name="A" data-category="Category_A" class="explore-cell">
        <h>A</h>
        <p>Category_A</p>
    </div>
    <div id="1232152351" data-name="C" data-category="Category_A" class="explore-cell">
        <h>C</h>
        <p>Category_A</p>
    </div>
    <div id="12342341" data-name="E" data-category="Category_B" class="explore-cell">
        <h>E</h>
        <p>Category_B</p>
    </div>
    <div id="1325321" data-name="D" data-category="Category_B" class="explore-cell">
        <h>D</h>
        <p>Category_B</p>
    </div>

</div>

java

$('div').sort(function (a, b) {

  var contentA = $(a).attr('data-name');
  var contentB = $(b).attr('data-name');
  return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;

})

Jsfiddle http://jsfiddle.net/w8gkshue/

Jsfiddle http://jsfiddle.net/w8gkshue/

如果有人可以正确地直接指导我如何最好地按产品名称或类别进行排序.

if someone can point me in the right direct on how to best sort either by Product Name or Category.

更新后希望能提供更好的爆炸效果

Updated hope this gives better explination

推荐答案

您可以使用.sort方法

You can use .sort method like this

var $wrapper = $('#ProductContainer');

$wrapper.find('.explore-cell').sort(function (a, b) {
    return a.getAttribute('data-name') > b.getAttribute('data-name');
})
.appendTo( $wrapper );

但是我不确定交叉浏览支持

But I don't sure about the cross browsing support

这篇关于根据数据属性对子div排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆