使用YouTube API构建视频画廊:点击视频Div获取父ID问题
Fixing Your YouTube Gallery Click Issue
Hey there, let's break down what's going wrong with your code and fix it step by step!
The Main Problems
Duplicate Event Bindings & Closure Trap
- You're binding the
clickevent inside the$.eachloop, which means every time the loop runs, you're adding a new click handler to all existing<font class="click">elements. By the end of the loop, the first element has 15 handlers attached—so clicking it triggers the function 15 times, hence the "累加" (accumulating) numbers you see. - Plus, because of JavaScript closures, all those handlers reference the same
idvariable. By the time you click any element, the loop has finished andidis already 15, so every click logs 15.
- You're binding the
Typo in Variable Name
- You wrote
iteaminstead ofitemin the$.eachcallback. This would cause an error when trying to accessitem.id.videoId, breaking your iframe URLs.
- You wrote
The Fixed Code
Here's the corrected version with explanations:
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script> $(document).ready(function(){ var id = 1; $.get( "https://www.googleapis.com/youtube/v3/search", { part: 'snippet', maxResults: 15, channelId: 'CHANNEL_ID', type: 'video', order: 'date', key: 'MY_KEY' }, function(data) { $.each( data.items, function( i, item ) { // Fixed "iteam" to "item" $('#content').append(` <div id="${id}"> <br> <iframe src="https://www.youtube.com/embed/${item.id.videoId}" class="youtube"></iframe> <p><font class="click">Get bigger</font></p> </div> `); id++; }); }); // Use event delegation to bind click ONCE, outside the loop $('#content').on('click', 'font.click', function(){ // Get the closest parent div's ID (more reliable than parent().parent()) const divId = $(this).closest('div').attr('id'); console.log(divId); }); }); </script> </head> <body> <div id="content"></div> </body> </html>
Key Improvements
- Event Delegation: Instead of binding handlers inside the loop, we bind a single handler to the parent
#contentelement. It listens for clicks on any childfont.clickelement (even dynamically created ones), which avoids duplicate bindings and closure issues. - Fixed Variable Typo: Changed
iteamtoitemso your iframe URLs work correctly. - Reliable ID Retrieval: Using
closest('div')ensures we always get the parent div's ID, even if your DOM structure changes slightly later.
Bonus: For the "Zoom" Feature
Since you mentioned wanting to make the <div> larger when clicked, you can add this to the click handler to achieve that:
$(this).closest('div').css({ transform: 'scale(1.2)', transition: 'transform 0.3s ease' });
(You might want to add some CSS to handle positioning or reset other divs if needed, but that's a starting point!)
内容的提问来源于stack exchange,提问作者here4onequestion
相关产品推荐
相关产品推荐

