为每个Iframe生成唯一ID,或从DOM节点构建Iframe

时间:2017-03-12 13:05:38

标签: javascript iframe

我需要为每个Iframe设置一个唯一的ID,以便正确呈现。我有一个递增的renderId变量。我试图将其附加到Iframe Id。

document.getElementById('iframe-test' + renderId);

此处的整个代码块:

let renderId = 0;
   const render = post => {
   renderId++;
   const node = document.createElement('div');
   node.innerHTML = `
     <h2 class="centered">
       <a href="${post.link}">
         <br>
             <iframe id="iframe-test" width="100%" min-height="100%" src="">
             </iframe>
         <br>
         ${post.title} 
         </a>
         <br><br>
         </h2>`;
         app.appendChild(node); 
         document.getElementById('iframe-test' + renderId);

没有视频显示。我尝试更改此行上的引号:

  <iframe id="iframe-test" width="100%" min-height="100%" src="">

在这一行之前我需要一些额外的步骤,但我不确定是什么。

  document.getElementById('iframe-test' + renderId);

完整应用:http://codepen.io/Teeke/pen/BWROeW

3 个答案:

答案 0 :(得分:2)

'<iframe id="iframe-test"'+renderId.toString()+' width="100%" min-height="100%" src="">'编辑:你只是忘了为每个div提供不同的ID。您正在寻找未分配的ID,因此我添加了renderId.toString。也许没有toString它会工作。不确定

答案 1 :(得分:1)

创建您独特的&#39; id在函数顶部的变量中:

let renderId = 0;
const render = post => {
    renderId++;
    const iframeId = `iframe-test-${renderId}`;
    const node = document.createElement('div');
    node.innerHTML = `<h2 class="centered">
                        <a href="${post.link}"><br>
                          <iframe id="iframe-test" width="100%" min-height="100%" src="">
                          </iframe>
                          <br>${post.title} 
                        </a>
                        <br><br>
                      </h2>`;
    app.appendChild(node);
    document.getElementById(iframeId);
}

或者,您可以使用YouTube参考作为ID:

// post.link (https://www.youtube.com/watch?v=TmIo702wjm4)

const uniqueId = `iframe-test-${post.link.substr(post.link.lastIndexOf('v=') +2)}`;

// iframe-test-TmIo702wjm4

答案 2 :(得分:0)

我最终用DOM节点构建了iframe。通过这种方式,我可以构建一个轻松重复的iframe,而无需为每个帧生成唯一的ID。这并不是根据原始问题实际生成ID,但它确实允许您复制没有唯一ID问题的Iframe div。我修改了问题的标题,以反映这个更广泛的解决方案。

HTML:

<div id="app"></div>

JS:

const app = document.querySelector('#app');
const render = post => {
 const node = document.createElement('div');  
   node.innerHTML= `${post.title}`;
  node.className= 'clip-title';
    app.appendChild(node);

var a = document.createElement('iframe');
a.className = "clip-content"
a.src = "https://www.youtube.com/embed/" + strippedURL; //add your iframe path here
a.width = "100%";
a.height = "100%";
a.padding = "500px";
app.style.textAlign = "center";
document.querySelector('#app').appendChild(a);