代码之家  ›  专栏  ›  技术社区  ›  emilywhou

使用文档创建的元素。createElement(),则未使用文档定义设置id。getElementById()稍后

  •  0
  • emilywhou  · 技术社区  · 7 年前

    请看这个 https://jsfiddle.net/vpLbvp0o/17/ 举个例子来说明我的问题。

    我正在尝试动态创建音频元素,在html页面上分层音乐。以下是我在创建新的音频元素和播放音乐时所做的操作:

    const new_layer = document.createElement("audio");
    new_layer.id = "hello";
    new_layer.src = "some_sound.mp3";
    new_layer.play();
    

    这样就行了,音乐开始播放。稍后,如果我想使用设置为暂停音乐或更新src的id引用同一个元素,请使用 document.getElementById("hello") 返回null。找不到元素,但音乐显然仍在DOM中播放。我如何引用这个我已经创建并且仍然存在的元素?在jsfiddle中,您可以看到,在尝试检索元素之前,我正在等待一个超时,但它似乎不在那里。

    如果我对HTML文档中已经定义的元素执行相同的操作,那么一切都正常。这是使用JavaScript动态创建元素的限制吗?

    2 回复  |  直到 7 年前
        1
  •  4
  •   bc1105    7 年前

    该节点不在DOM中,您需要添加它。

    document.body.appendChild(new_layer);

        2
  •  0
  •   Thum Choon Tat    7 年前

    document.getElementById 获取具有指定 id 从…起 document ,并且您没有将其附加到文档中

    const player = document.createElement("AUDIO");
    player.setAttribute("id", "hello");
    player.src = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3";
    player.play();
    console.log(player.id);
    console.log(player);
    
    document.body.appendChild(player);
    
    let get_player;
    let audio_list;
    setTimeout(function() {
    	get_player = document.getElementById("hello");
    	audio_list = document.getElementsByTagName("audio"); 
    
      console.log(get_player);
      console.log(audio_list);
    }, 1000);
    
    // Try pausing and playing the audio element. It does not work.
    setTimeout(function() { get_player.pause(); }, 5000);
    setTimeout(function() { get_player.play(); }, 10000);
    <audio id="ambient"></audio>
    <audio id="background"></audio>