.sort()
関数を使用できますが、配列で動作するjavascript関数なので、すべての要素を配列に配置する必要があります。そのためには、.get()
jquery関数を使用して、一連のjqueryオブジェクトを取得し、それをDOM要素の配列に変換することができます。
すべて一緒に置く...
$('button#views').click(function() {
// Get all your videoframe divs and convert it in an array of DOM elements.
var videos = $('div.videoframe').get();
// Sort the array based in the value of the div.counter value (descendent).
videos.sort(function(a,b) {
return parseInt($(b).find('div.counter').text()) - parseInt($(a).find('div.counter').text());
});
// Replace current content with the new ordered set of elements.
$('body').html($(videos));
});
そして、ここであなたはフィドルの例を持っている... https://fiddle.jshell.net/rigobauer/858u58a7/3/
EDITED:どうやら
、すべてのあなたのdiv.videoframe
のコンテナをしたいですコンテナの内側にあることdiv
。最も簡単なアプローチは、HTMLコード内の空のコンテナを作成し(コンテンツを追加する場所に配置する)、body
の代わりにそのコンテナにレスポンスを直接追加することです。何らかの理由であなたがHTMLを変更することができない場合は、getJSON
コール(ここでは、あなたがbody
要素OD最後に追加の例を持っている)...
<script>
$('body').append('<div class="container"></div>');
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Qq7mpb-hCBY&key=[key]', function(data) {
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=snippet&id=mxHB21dKmkw&key=[key]', function(data2) {
$('div.container').append('<div class = videoframe><div class = video><iframe src=https://www.youtube.com/embed/XGSy3_Czz8k width = 98.5% height = 140 allowfullscreen =allowfullscreen></iframe><div class = counter>'+data.items[0].statistics.viewCount +'</div><div class = title>'+ data2.items[0].snippet.title+'</div></div></div>');
});
});
</script>
前にjQueryを使って、そのコンテナを追加することができます
...ソートコードが少し変わります...
$('button#views').click(function() {
// Get all your videoframe divs and convert it in an array of DOM elements.
var videos = $('div.container div.videoframe').get();
// Sort the array based in the value of the div.counter value (descendent).
videos.sort(function(a,b) {
return parseInt($(b).find('div.counter').text()) - parseInt($(a).find('div.counter').text());
});
// Replace current content with the new ordered set of elements.
$('div.container').html($(videos));
});
非常に参考になりました。 問題はあります。 私が言ったように、私のコードは面倒です、私は大きなdivでそれらをセットアップすることはできません、そこに追加されたすべてのビデオは、実際にそれを把握しようとしている現時点では本当に問題です。 もしそれらのすべてを1つのdivに入れることができれば、あなたの例を使うことができます。 –
私はスクリーンショットを撮ったので、私は何を意味するのかを見ることができます: https://gyazo.com/d573b29d931897404c57177bdacf7851 –
ただ一つの 'div'は必要ありません。私の解決策はあなたの場合です。各ビデオに1つのdivがあります。あなたはフィドルをチェックしましたか? HTMLはあなたの質問に表示されているコードに基づいています(ビデオごとに1つの 'div.videoframe') –