我想为类.youtube_add_to_playlist
的元素添加一个事件触发器。此元素是动态添加的。
到目前为止我尝试了什么
我将整个代码整理到$(document).ready(function() { });
我换了:
jQuery('.youtube_add_to_playlist').click(function(e)
与
jQuery(document).on('click', '.youtube_add_to_playlist', function(e)
事件触发器仍未添加到元素中。显然,我错过了一些东西。可能我在函数中使用.on()
...?
jQuery(document).ready(function() {
var OAUTH2_CLIENT_ID = '';
var OAUTH2_SCOPES = ['https://www.googleapis.com/auth/youtube'];
var init = false;
var youtube_button = null;
googleApiClientReady = function() {
gapi.auth.init(function() {
window.setTimeout(checkAuth, 1);
});
}
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);
}
// Handle the result of a gapi.auth.authorize() call.
function handleAuthResult(authResult) {
jQuery('.youtube_add_to_playlist').off('click');
///jQuery('.youtube_add_to_playlist').click(function(e) {
jQuery(document).on('click', '.youtube_add_to_playlist', function(e) {
youtube_button = this;
if (authResult && !authResult.error) {
addToPlaylist(jQuery(this).attr("data-youtube-video-id"), jQuery(this).attr("data-type"));
} else {
init = true;
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
}
return false;
});
if (authResult && !authResult.error) {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
jQuery('.pre-auth').hide();
jQuery('.post-auth').show();
loadAPIClientInterfaces();
jQuery('#add_to_wl').click(function(e) {
youtube_button = this;
addToPlaylist(jQuery(this).attr("data-youtube-video-id"), jQuery(this).attr("data-type"));
});
}
}
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', function() {
if (init) {
init = false;
addToPlaylist(jQuery(youtube_button).attr("data-youtube-video-id"), jQuery(youtube_button).attr("data-type"));
}
});
}
function addToPlaylist(videoId, playlistType) {
console.log("add to playlist type : " + playlistType);
if (playlistType != "WL" && playlistType != "HL") {
var request = gapi.client.youtube.channels.list({
mine: true,
part: 'contentDetails'
});
request.execute(function(response) {
var playlistId = response.result.items[0].contentDetails.relatedPlaylists[playlistType];
if (typeof playlistId != 'undefined') {
console.log("found playlist id : " + playlistId);
insertToPlaylist(videoId, playlistId);
} else {
console.log("playlist not found");
}
});
} else {
insertToPlaylist(videoId, playlistType);
}
}
function insertToPlaylist(videoId, playlistId) {
var details = {
videoId: videoId,
kind: 'youtube#video'
};
var request = gapi.client.youtube.playlistItems.insert({
part: 'snippet',
resource: {
snippet: {
playlistId: playlistId,
resourceId: details
}
}
});
request.execute(function(response) {
console.log(response);
if (!response.code) {
// do stuff
}
});
}
});