【问题标题】:SetAttribute on a specific position in Javascript在 Javascript 中的特定位置上设置属性
【发布时间】:2022-01-05 00:11:49
【问题描述】:

我有以下iframe

<iframe frameborder="0" src="//www.youtube.com/embed/adLvq2haaFg" class="note-video-clip"></iframe>

当我像这样定位iframegetElementsByTagName

let a = document.getElementsByTagName("iframe")[0];
a.setAttribute('allowfullscreen', '');

返回:

<iframe frameborder="0" src="//www.youtube.com/embed/adLvq2haaFg" class="note-video-clip" allowfullscreen=""></iframe>

这给我带来了问题,因为它没有按预期工作。当我在开始时手动插入 allowfullscreen 时,它运行良好。

这是我想要的结果

<iframe allowfullscreen="" frameborder="0" src="//www.youtube.com/embed/adLvq2haaFg" class="note-video-clip" ></iframe>

我做错了什么?

【问题讨论】:

  • setAttribute("allowFullScreen", true); 怎么样?

标签: javascript html iframe


【解决方案1】:

在标签名称后添加allowfullscreen="" 的一种简单方法是使用字符串方法split 和数组方法splice 修改元素的outerHTML,如下面的代码所示。

const miFrame = document.getElementsByTagName("iframe")[0];
console.log(miFrame);

// Split the outerHTML string into separate pieces
// by using a space as the separator
const miFrameOH = miFrame.outerHTML.split(' ');

// Using splice(position, deleteCount, itemToAdd),
// add attribute at index 1
miFrameOH.splice(1, 0, 'allowfullscreen=""');

// Join the parts (including the attribute) with a space separator and
// set this string to the outerHTML
miFrame.outerHTML = miFrameOH.join(' ');
console.log(document.getElementsByTagName("iframe")[0].outerHTML);
&lt;iframe frameborder="0" src="//www.youtube.com/embed/adLvq2haaFg" class="note-video-clip"&gt;&lt;/iframe&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-02
    • 2022-11-12
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    • 2021-09-14
    • 2011-07-08
    • 2015-08-19
    相关资源
    最近更新 更多