我的元素很少:
https://jsfiddle.net/vvbpvt0c/
<figure class="img-space">
<img src="http://placehold.it/150/30ac17" alt="qwqwqwaccusamus beatae ad facilis cum similique qui sunt">
<figcaption class="text-img">accusamus beatae ad facilis cum similique qui sunt</figcaption></figure>
我希望通过img [alt]对它们进行排序并在侧面显示,sort()不起作用。
答案 0 :(得分:0)
所以这是一种可能的方式。排序完成后,他们按照figcaption进行排序。如果你想通过alt文本来做,那么你可能想要确保它们都有一个alt并且只需使用$(a).find(“img”)。attr(“alt”)而不是我使用的选择器。在信用到期的情况下,我使用http://james.padolsey.com/snippets/sorting-elements-with-jquery/作为起点。
jQuery.fn.sortElements = (function() {
var sort = [].sort;
return function(comparator, getSortable) {
getSortable = getSortable || function() {
return this;
};
var placements = this.map(function() {
var sortElement = getSortable.call(this),
parentNode = sortElement.parentNode,
// Since the element itself will change position, we have
// to have some way of storing its original position in
// the DOM. The easiest way is to have a 'flag' node:
nextSibling = parentNode.insertBefore(
document.createTextNode(''),
sortElement.nextSibling
);
return function() {
if (parentNode === this) {
throw new Error(
"You can't sort elements if any one is a descendant of another."
);
}
// Insert before flag:
parentNode.insertBefore(this, nextSibling);
// Remove flag:
parentNode.removeChild(nextSibling);
};
});
return sort.call(this, comparator).each(function(i) {
placements[i].call(getSortable.call(this));
});
};
})();
$("button").on("click", function() {
$("figure").sortElements(function(a, b) {
var aStr = $(a).find("figcaption").text().toUpperCase(),
bStr = $(b).find("figcaption").text().toUpperCase();
return aStr.localeCompare(bStr);
})
})
img {
float: left;
}
figcaption {
float: left;
margin-left: 5px;
width: 100px;
}
figure {
clear: both;
height: 175px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="sort">
Sort them!
</button>
<figure class="img-space">
<img src="http://placehold.it/150/30ac17" alt="accusamus beatae ad facilis cum similique qui sunt">
<figcaption class="text-img">accusamus beatae ad facilis cum similique qui sunt</figcaption>
</figure>
<figure class="img-space">
<img src="http://placehold.it/150/30ac17" alt="accusamus beatae ad facilis cum similique qui sunt">
<figcaption class="text-img">aaassaccudsasamus beatae ad facilis cum similique qui sunt</figcaption>
</figure>
<figure class="img-space">
<img src="http://placehold.it/150/30ac17" alt="accusamus beatae ad facilis cum similique qui sunt">
<figcaption class="text-img">fdsffsfsaccusamus beatae ad facilis cum similique qui sunt</figcaption>
</figure>