找到某事物的父ID

时间:2018-01-03 14:25:48

标签: javascript jquery html youtube-api youtube-data-api

我正在尝试使用YouTube API创建一个视频库,我想要点击视频所在的<div><div>会变得更大。代码:

$(document).ready(function(){
  var n,
  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, iteam ) {
          $('#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>');
          $('font.click').click(function(){
            console.log($(this).parent().attr('id')); // Here I want it to write 
            //in console specific id of the
            //`<div>` I click, but it writes 15, which is 
            //the final value of `id` variable, because I 
            //click it when all the videos load. And also 
            //when I click it twice it writes 30, when 
            //thrice - 45 and etc. So I don't know how to 
            //get the specific id of the only `div` I click.
          });
          id++;
        })
      }
  );
});
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
  <div id="content">
  </div>
</body>
</html>

我非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

好的,这是一个小解释。

$(document).ready(function(){
  var n,
  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, iteam ) {
         $('#content').append('
           <div id="googleVid-' + 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++;
       });
     }
   ).always(function() {
       $('font.click').click(function(){
          console.log($(this).closest('div').attr('id'));
       });
   });       
});
  1. 修正了html
  2. 查看字体的父级是什么。这是 p 标签而不是div
  3. 最近而不是父级会找到最接近的 div 标记doc
  4. 点击活动已移至document.ready

答案 1 :(得分:0)

试试这个:$(this).parent().prev().attr('id')

在你&#39; html&#39;你有iframe~p>font

而$(this)指的是font