首页 > 解决方案 > 如何将抓取 YouTube 标题的 jQuery 转换为功能

问题描述

我有以下获取 YouTube 标题的 jQuery 代码。

$.getJSON('https://www.googleapis.com/youtube/v3/videos?id={VIDEOID}&key={YOUR API KEY}&part=snippet&callback=?',function(data){
    if (typeof(data.items[0]) != "undefined") {
        console.log('video exists ' + data.items[0].snippet.title);
       } else {
        console.log('video not exists');
     }   
    });

我想将它作为一个函数,以便我可以将 YouTube id 作为参数传递。

标签: javascriptjquery

解决方案


如果你想把它变成一个函数,这很容易做到:

function youtubeVideo(videoID, apiKey) {

   $.getJSON('https://www.googleapis.com/youtube/v3/videos?id='+videoID+'&key='+apiKey+'&part=snippet&callback=?',function(data){
    if (typeof(data.items[0]) != "undefined") {
        console.log('video exists ' + data.items[0].snippet.title);
       } else {
        console.log('video not exists');
     }   
    });

}

请注意,我们将 videoID 和 apiKey 传递给函数。为了调用它,您只需:

youtubeVideo(video_id_here, api_key_here);

推荐阅读