【问题标题】:Get the ID of a specific div when subscribing to a Youtube channel订阅 Youtube 频道时获取特定 div 的 ID
【发布时间】:2015-12-31 17:53:52
【问题描述】:

当用户订阅或取消订阅时,我需要显示 Youtube 频道的名称。

下面是两个订阅按钮和一个事件脚本。

<script src="https://apis.google.com/js/platform.js"></script>

<div id="chan-1" class="g-ytsubscribe" data-channel="SMOSH" data-layout="default" data-count="default" data-onytevent="onYtEvent"></div>
</div>

<div id="chan-2" class="g-ytsubscribe" data-channel="Apple" data-layout="default" data-count="default" data-onytevent="onYtEvent"></div>
</div>

<script>
  function onYtEvent(payload) {

    if (payload.eventType == 'subscribe') {
      // Need to display subscribed channel name

    } else if (payload.eventType == 'unsubscribe') {
      // Need to display unsubscribed channel name

    }
    if (window.console) { // for debugging only
      window.console.log('YT event: ', payload);
    }
  }
</script>

【问题讨论】:

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


    【解决方案1】:

    您可以通过多种方式做到这一点。

    1. 将payload参数中传递的外部id与频道id匹配

      payload 参数包含 channelExternalId,其中包含该频道的 youtube id。您可以保留要显示的频道的外部 ID 列表,以及 ytevent 触发时将 channelExternalId 匹配到正确的频道名称

      var channelNamesById = {
         "UCY30JRSgfhYXA6i6xX1erWg":"SMOSH",
         "UCE_M8A5yxnLfW0KghEeajjw":"Apple"
      };
      function onYtEvent(payload){
          var channelName = channelNamesById[payload.channelExternalId];
      }
      

      有几种方法可以获取频道 ID,see here

    2. 动态创建按钮,并将频道名称.bind 传递给 ytevent 回调函数,该回调函数会将频道名称作为参数传递

      该 api 还允许您动态创建按钮。当您以这种方式创建按钮时,您可以将通道名称传递给回调函数

      HTML

      <div id="chan-1"></div>
      <div id="chan-2"></div>
      

      JS

      gapi.ytsubscribe.render(
         document.querySelector("#chan-1"),
         {
             "channel": "SMOSH", 
             "layout": "default",
             "count":"default",
             "onytevent":onYtEvent.bind(null,"SMOSH")
         }
      );
      gapi.ytsubscribe.render(
        document.querySelector("#chan-2"),
        {
             "channel": "Apple", 
             "layout": "default",
             "count":"default",
             "onytevent":onYtEvent.bind(null,"Apple")
        }
      );
      
      function onYtEvent(channelName,payload) {
          console.log(channelName);
      }
      

    您还可以使用 api 执行 ajax 请求以获取频道详细信息,其中应包括其名称,但由于您已经在代码中拥有频道名称,因此我没有介绍该选项。 api for channels

    【讨论】:

      【解决方案2】:

      您可以使用以下代码:

          var divs = $('div#chan-1').attr('id');
      

      获取&lt;div id="chan-1"&gt;的ID。

      一个 JS Bin 例子:http://jsbin.com/mazasegawu/edit?html,output

      【讨论】:

      • 所以你是说你可以使用选择器#chan-1 来找出id 是chan-1
      猜你喜欢
      • 1970-01-01
      • 2019-02-15
      • 2015-03-27
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 2021-02-19
      • 1970-01-01
      相关资源
      最近更新 更多