从YouTube API排序搜索结果表



我试图创建一个可排序的搜索结果表从YouTube返回。我可以很好地创建搜索引擎,我可以创建一个排序表。但现在我想把两者联系起来。

我知道主要的问题是,当页面加载没有结果排序;在执行搜索之前没有表。

我看了这个讨论,我认为有一些东西可以让我工作,但我不知道如何整合它。

这是我目前正在做的:

app.js

function tplawesome(e, t) {
res = e;
for (var n = 0; n < t.length; n++) {
    res = res.replace(/{{(.*?)}}/g, function(e, r) {
        return t[n][r];
    });
}
return res;
}
$(function() {
$("form").on("submit", function(e){
    e.preventDefault();
    // prepare the request
    var request = gapi.client.youtube.search.list({
        part: "snippet",
        type: "video",
        q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"),
        maxResults: 5,
        publishedAfter: "2015-01-01T00:00:00Z",
        relevanceLanguage: "en"
    });
    // execute request
    request.execute(function(response) {
        // console.log(response);   // test by logging to console
        var results = response.result;
        $("#results").html("");     // reset results
        // loop through each returned item
        $.each(results.items, function(index, item) {
            console.log(item);      // test by logging to console
            $.get("tpl/results-sortable-table.html", function(data) {
                $("#results").append(tplawesome(data,
                    [{
                        "title": item.snippet.title,
                        "description": item.snippet.description,
                        "channelTitle": item.snippet.channelTitle,
                        "publishedAt": item.snippet.publishedAt,
                    }]
                ));
            });
        });
        resetVideoHeight();
    });
});
$(window).on("resize", resetVideoHeight);   // reset video height when window is resized
});
function resetVideoHeight() {
$(".video").css("height", $("#results").width() * 9/16);
}
function init() {
gapi.client.setApiKey("");      // Removed on purpose
gapi.client.load("youtube", "v3", function() {
    // yt api is ready
});
}

// THE SORTING SCRIPT
// I think I need to include something here that listens for when the table is populated. Is that right?
// --------------------------------------------------------------------
// COMPARE OBJECT
// --------------------------------------------------------------------
// Create a general "compare" object that will compare values in a table
    var compare = {
        name: function(a, b) {              // For genre and title (data-type = name) ...
            a = a.replace(/^the /i, '');    // Remove "the" from start (^) of parameter a ...
            b = b.replace(/^the /i, '');    // and parameter "b".
            a = a.replace(/^a /i, '');      // Remove "a" from start (^) of parameter a ...
            b = b.replace(/^a /i, '');      // and parameter "b".
            a = a.replace(/^an /i, '');     // Remove "a" from start (^) of parameter a ...
            b = b.replace(/^an /i, '');     // and parameter "b".
            a = a.toUpperCase();            // Convert a to uppercase
            b = b.toUpperCase();            // Convert b to uppercase
            if (a < b) {                    // If a is less than b ...
                return -1;                  // ???????? return -1 indicating a should be before b, ...
            } else {                        // otherwise ...
                return a > b ? 1 : 0;       // return 1 if a is greater than b or ...
            }                               // return zero (if the are the same).
        },
// --------------------------------------------------------------------
// DATE METHOD
// --------------------------------------------------------------------
// Create a "date" method that will compare and sort two dares by using the date function to ...
// convert string to date, and sort them based on their values.
    date: function(a, b) {                  // Add a method called date
        a = new Date(a);                    // New Date object to hold the date
        b = new Date(b);                    // New Date object to hold the date
        // Compare dates and return result
        return a > b ? 1 : 0;               // return 1 if a is greater than b or ...
                                            // return zero (if the are the same).               
    },
};
// --------------------------------------------------------------------
// SORT TABLE SCRIPT
// --------------------------------------------------------------------
$('.sortable').each(function() {
// Establish variables
var $table = $(this);                       // The current sortable table.
var $tbody = $table.find('tbody');          // Store this table's tbody in $tbody.
var $thcontrols = $table.find('th');        // Store this table's th in $thcontrols.
var rows = $tbody.find('tr').toArray();     // Store an array of tr's in rows.
$thcontrols.on('click', function() {    // When user clicks on a th
    var $th = $(this);                  // Get the th that was clicked on
    var datasort = $th.data('sort');    // Get value of this th's data-sort attribute and store it in datasort.
    var column;                         // Declare the column variable. 
    // If selected item already has ascending or descending class, then it's already sorted so reverse contents.
    if ($th.is('.ascending') || $th.is('.descending')) {    // If th is .ascending or .descending ...
        $th.toggleClass('ascending descending');            // switch their classes and ...
        $tbody.append(rows.reverse());                      // Reverse the headers array of rows.
    } else {                                                // Otherwise perform a sort                            
        // If compare object has method that matches the value of the data-type attribute for this column ...
        if (compare.hasOwnProperty(datasort)) {     // Note: datasort is $th.data('sort')
            column = $thcontrols.index(this);       // ... get the th's index number.
            rows.sort(function(a, b) {                  // Sort values in rows array.
                a = $(a).find('td').eq(column).text();  // Find text of the td in the column in row a, ...
                b = $(b).find('td').eq(column).text();  // find text of the td in the column in row b and ...
                return compare[datasort](a, b);         // compare them.
            });
        $th.addClass('ascending');                          // Add .ascending to th and ...
        $th.siblings().removeClass('ascending descending'); // remove asc or desc from all other headers. And ...
            $tbody.append(rows);    // Append the rows to the table body
        }
    }
}); 
});

index . html

<!DOCTYPE html>
<html lang="en">
<head>      
    <title>YouTube Search Engine</title>
    <meta charset="UTF-8" />                    
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Awesome videos!" />
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/sort-table.css">
</head>
<body>
    <header>
        <h1 class="w100 text-center"><a href="index.html">YouTube Viral Search</a></h1>
    </header>
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <form action="#">
                <p><input type="text" id="search" placeholder="Type something..." autocomplete="off" class="form-control" /></p>
                <p><input type="submit" value="Search" class="form-control btn btn-primary w100"></p>
            </form>

    <table class="sortable">
        <thead>
            <tr>
                <th data-sort="name">Title</th>
                <th data-sort="name">Description</th>
                <th data-sort="name">Channel Title</th>
                <th data-sort="date">Published At</th>
            </tr>
        </thead>
        <tbody id="results">
            <!-- results go here -->                
        </tbody>
    </table>        
    </div>
    </div>
    <!-- scripts -->
    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="js/app.js"></script>
    <script src="https://apis.google.com/js/client.js?onload=init"></script>
</body>
</html>

results-sortable-table.html

<tr onload="sort()" class="item">
    <td>{{title}}</td>
    <td>{{description}}</td>
    <td>{{channelTitle}}</td>
    <td>{{publishedAt}}</td>
</tr>

我知道我把所有的东西都放在这里了,但是我对这些都很熟悉,所以我不确定哪些是重要的。

感谢所有能帮助我的人,

Aryadne

我知道主要的问题是,当页面加载没有结果排序;在执行搜索之前没有表。

有几件事可以让你在正确的方向和解决你上面的报价:

  1. 从每行删除排序加载
  2. 将你的代码包装成一个函数$('.sortable').each(function() {
  3. 只有当所有结果都被添加到页面中时才调用此函数。-直接呼叫resetVideoHeight();

最新更新