我需要帮助排序一些youtube视频的视图计数,这是我使用的脚本嵌入youtube视频与视频观看计数和标题在网站上(抱歉,如果有点混乱):
<script>
$.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){
{$('body').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>想象一下,这个脚本里面有100+ youtube视频(放在我的身体里),我想要一个按钮,可以按下的按钮,根据观看次数对youtube视频进行排序。
我对Jquery不是很有经验,这就是为什么我在这个很棒的论坛/帮助服务上寻求帮助的原因。我对Jquery的“排序处理”有一点了解,但还不足以理解如何在这种情况下进行排序。
发布于 2017-10-22 08:47:09
您可以使用.sort()函数,但它是一个适用于数组的javascript函数,因此需要将所有元素放入一个数组中。为此,您可以使用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/
编辑的
显然,您希望所有的div.videoframe容器都在容器div中。最简单的方法是在HTML代码中创建空容器(将其定位在要添加内容的位置),然后将响应添加到该容器,而不是直接添加到body。如果由于某些原因无法修改HTML,则可以在jQuery调用之前使用getJSON添加容器(这里有一个将其添加到body元素末尾的示例).
<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>..。排序代码会有一点变化..。
$('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));
});https://stackoverflow.com/questions/46869367
复制相似问题