2012-02-10 2 views
1

내 HTML에 embed 태그가 있는지 어떻게 확인할 수 있습니까? 나는 자바 스크립트check embed tag 존재 여부 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를 사용하면 많은 embed 태그가 있다고 생각합니다. 그것이 제가 생각하기에 추가 사운드의 원인이라고 생각합니다.

답변

3

추가하기 전에 soundEmbed.id = "__soundEmbed";을 추가하십시오. 그런 다음 전체 내용을 다음과 같이 묶으십시오.

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

HTML에는 없지만 DOM 트리에 있습니다 (HTML을 구문 분석 한 후에 DOM에 추가하므로 HTML이 전혀 표시되지 않습니다). 매우 간단한 솔루션은 아직 생성되었는지 아닌지를 알려주는 전역 변수를 유지하는 것입니다. 으로 초기화하고 embed 요소를 만들 때 true으로 설정하면됩니다.

당신은 요소에게 ID를 부여하고 확인할 수 있습니다
1

이 첫 번째 :

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');'이게 맞습니까? –

+0

soundEmbed가있는 경우 어떻게 소리를 재생할 수 있습니까? 사운드가없는 경우에만 재생됩니다. –