javascript - 从div插入文本到api调用embed

时间:2011-08-29 08:13:08

标签: javascript embed

我有以下基本脚本来对vimeo进行api调用并将embed插入到div #embed中。我遇到麻烦然后让它抓住另一个div #embedthis的文本并组装api调用。

如果放在<body>中,则下面的代码可以正常工作。但是我想正确设置它,因为我还希望能够动态更改#embedthis的内容,更新显示的嵌入。任何帮助都非常感谢!

脚本:

  // URL to get embed
  var videoUrl = document.getElementById('embedthis').innerHTML; 

  // oEmbed endpoint for Vimeo using JSON

  var endpoint = 'http://www.vimeo.com/api/oembed.json';

  // Tell Vimeo what function to call
  var callback = 'embedVideo';

  // Put together the URL
  var url = endpoint + '?url=' + encodeURIComponent(videoUrl) + '&callback=' + callback + '&width=640';

  // put video on page
  function embedVideo(video) {
      document.getElementById('embed').innerHTML = unescape(video.html);
  }

  // load data from Vimeo
  function MakeEmbed() {
      var js = document.createElement('script');
      js.setAttribute('type', 'text/javascript');
      js.setAttribute('src', url);
      document.getElementsByTagName('head').item(0).appendChild(js);
  };

  window.onload = MakeEmbed;

视图:

<div id="embed">
  ...
</div>

<div id="embedthis">http://vimeo.com/24453255</div>

有了这个,我得到document.getElementById('embedthis')" is null,可能是因为#embedthis尚未加载。

1 个答案:

答案 0 :(得分:0)

问题在于,当var videoUrl = document.getElementById('embedthis').text()被调用时,浏览器尚未创建<div>,因为一旦浏览器遇到它就会调用此代码,我认为这是在你的<head>部分。

如果将代码移动到window.onloaddocument.ready上调用的函数,则代码应该有效,因为这可以保证元素已经创建。

修改

像这样(为简洁起见删除了评论):

var url;
function embedVideo(video) { ... }

var my_onload = function() {
    var videoUrl = document.getElementById('embedthis').innerHTML; 
    var endpoint = 'http://www.vimeo.com/api/oembed.json';
    var callback = 'embedVideo';
    url = endpoint + '?url=' + encodeURIComponent(videoUrl) + '&callback=' + callback + '&width=640';
    MakeEmbed();
}

window.onload = my_onload;