我试图将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/

非常感谢您的帮助。

最佳答案

使用下面的代码。它接近您的功能。它获取数据属性“ ename”并返回它。
$(a).data('ename')代替+a.getAttribute('data-ename')



var $wrapper = $('.modal .row');

$wrapper.find('.txt_center').sort(function (a, b) {
    return $(a).data('ename') > $(b).data('ename');
}).appendTo($wrapper);

<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>

关于jquery - 按数据属性按字母顺序放置div,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31658700/

10-11 05:56