You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用YouTube API构建视频画廊:点击视频Div获取父ID问题

Hey there, let's break down what's going wrong with your code and fix it step by step!

The Main Problems

  1. Duplicate Event Bindings & Closure Trap

    • You're binding the click event inside the $.each loop, 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 id variable. By the time you click any element, the loop has finished and id is already 15, so every click logs 15.
  2. Typo in Variable Name

    • You wrote iteam instead of item in the $.each callback. This would cause an error when trying to access item.id.videoId, breaking your iframe URLs.

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 #content element. It listens for clicks on any child font.click element (even dynamically created ones), which avoids duplicate bindings and closure issues.
  • Fixed Variable Typo: Changed iteam to item so 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:02:16