【问题标题】:check embed tag exist javascript检查嵌入标签是否存在 javascript
【发布时间】:2012-03-03 02:54:43
【问题描述】:

如何检查我的 html 中是否存在嵌入标签。 我已经通过 javascript 创建了这个标签

    soundEmbed = document.createElement("embed");
    soundEmbed.setAttribute("src", "notify.wav");
    soundEmbed.setAttribute("hidden", true);
    soundEmbed.setAttribute("autostart", true);
    soundEmbed.setAttribute("loop", false);
    document.body.appendChild(soundEmbed);

但由于我使用的是 autorefresh 和 appendChild,所以每次刷新都会产生额外的声音。

使用 appendChild,我想我有很多嵌入标签。这就是我认为可能产生额外声音的原因。

【问题讨论】:

    标签: javascript tags embed append element


    【解决方案1】:

    在追加之前添加soundEmbed.id = "__soundEmbed";。然后,用以下内容包围整个事物:

    if( !document.getElementById("__soundEmbed")) {
        soundEmbed = ......;
        ......
    }
    

    【讨论】:

      【解决方案2】:

      您可以给元素一个 id 并首先检查:

      if (!document.getElementById('someId')) {
        var soundEmbed = document.createElement("embed");
        soundEmbed.setAttribute("src", "notify.wav");
        soundEmbed.setAttribute("hidden", true);
        soundEmbed.setAttribute("autostart", true);
        soundEmbed.setAttribute("loop", false);
        soundEmbed.setAttribute("id", 'someId');
        document.body.appendChild(soundEmbed);
      }
      

      或者,检查一个标志(因为 soundEmbed 似乎在其他地方定义,我们可以对其使用错误检查):

      if (!soundEmbed) {
        soundEmbed = document.createElement("embed");
        soundEmbed.setAttribute("src", "notify.wav");
        soundEmbed.setAttribute("hidden", true);
        soundEmbed.setAttribute("autostart", true);
        soundEmbed.setAttribute("loop", false);
        document.body.appendChild(soundEmbed);
      }
      

      【讨论】:

      • 我可以删除元素吗?然后添加孩子?我需要这种方式是有原因的。示例:if (document.getElementById('soundId')) document.body.removeChild('soundId'); 是这样吗?
      • 如果存在 soundEmbed,如何播放声音?仅在没有 soundEmbed 时播放
      【解决方案3】:

      它不会出现在您的 HTML 中,但会出现在 DOM 树中(您在解析 HTML 后将其添加到 DOM,因此它永远不会看到任何 HTML)。一个超级简单的解决方案是只维护一个全局变量,告诉您它是否已创建 - 只需将其初始化为 false,并在创建 embed 元素时将其设置为 true

      【讨论】:

        猜你喜欢
        • 2011-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-08
        • 2023-04-02
        相关资源
        最近更新 更多