2012-02-10 32 views
1

如何檢查嵌入標記是否存在於我的html中。 我已經通過JavaScript檢查嵌入標記是否存在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); 

創造了這個標籤,但自從我使用自動刷新和使用appendChild,每次都刷新它創造更多的聲音。

使用appendChild,我想我有很多嵌入標籤。這就是我認爲可能導致額外聲音的原因。

回答

3

在追加之前添加soundEmbed.id = "__soundEmbed";。然後,圍繞整個東西:

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

它不會在你的HTML中,但它會在DOM樹中(你在HTML解析後將它添加到DOM中,所以它不會看到任何HTML)。一個超級簡單的解決方案是隻保留一個全局變量,告訴你它是否已經創建 - 只需將其初始化爲false,並在創建embed元素時將其設置爲true

1

你可以給該元素的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似乎是其他地方定義,我們可以使用它falsey檢查):

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); 
} 
+0

我可以只刪除元素?然後添加孩子?我需要這種方式是有原因的。示例:'if(document.getElementById('soundId'))document.body.removeChild('soundId');'這是正確的嗎? – 2012-02-10 16:46:10

+0

如果soundEmbed存在,我該如何播放聲音?它只在沒有soundEmbed時播放 – 2012-02-10 17:06:22