按数据属性按字母顺序放置div

时间:2015-07-27 16:42:05

标签: jquery

我试图将我的div按字母顺序排列,并且使用我的jQuery代码失败:

var $wrapper = $('.modal .row');
$wrapper.find('.txt_center').sort(function (a, b) {
return +a.getAttribute('data-ename') > +b.getAttribute('data-ename'); }).appendTo($wrapper);

html代码如下:

<div class="modal" id="staff" style="text-align: center;">

<div class="row txt_center">
    <div class="txt_center" data-ename="William Black">
        <p class="profile-name"><strong>William Black</strong>

        </p>
        <p class="profile-details">Title</p>
    </div>
    <div class="txt_center" data-ename="Ariel White">
        <p class="profile-name"><strong>Ariel White</strong>

        </p>
        <p class="profile-details">Title</p>
    </div>
    <div class="txt_center" data-ename="John Smith">
        <p class="profile-name"><strong>John Smith</strong>

        </p>
        <p class="profile-details">Title</p>
    </div>
    <div class="txt_center" data-ename="Vanessa Mae">
        <p class="profile-name"><strong>Vanessa Mae</strong>

        </p>
        <p class="profile-details">Title</p>
    </div>
</div>

请帮我解决JSfiddle的问题:http://jsfiddle.net/8rhg4337/1/

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

使用以下代码。它接近你的功能。它获取数据属性&#39; ename&#39;并返回它。 $(a).data('ename')代替+a.getAttribute('data-ename')

&#13;
&#13;
var $wrapper = $('.modal .row');

$wrapper.find('.txt_center').sort(function (a, b) {
    return $(a).data('ename') > $(b).data('ename');
}).appendTo($wrapper);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal" id="staff" style="text-align: center;">

<div class="row txt_center">
    <div class="txt_center" data-ename="William Black">
        <p class="profile-name"><strong>William Black</strong>

        </p>
        <p class="profile-details">Title</p>
    </div>
    <div class="txt_center" data-ename="Ariel White">
        <p class="profile-name"><strong>Ariel White</strong>

        </p>
        <p class="profile-details">Title</p>
    </div>
    <div class="txt_center" data-ename="John Smith">
        <p class="profile-name"><strong>John Smith</strong>

        </p>
        <p class="profile-details">Title</p>
    </div>
    <div class="txt_center" data-ename="Vanessa Mae">
        <p class="profile-name"><strong>Vanessa Mae</strong>

        </p>
        <p class="profile-details">Title</p>
    </div>
</div>
&#13;
&#13;
&#13;