2017-02-19 33 views
0

我想了解JS引用。在Javascript中引用變量的元素屬性

<a id="ohnoes" href="https://www.kasandbox.org/programming-sounds/rpg/giant-no.mp3">What does Oh Noes say?</a>` 

所以我在這裏引用上面的標籤在這個函數:

var ohnoesEl = document.getElementById("ohnoes"); 
var onOhNoesClick = function(e) { 
    e.preventDefault(); 
    var audioEl = document.createElement("audio"); 
    audioEl.src = "https://www.kasandbox.org/programming-sounds/rpg/giant-no.mp3"; 
    audioEl.autoplay = "true"; 
    document.body.appendChild(audioEl); 
    }; 

爲什麼這項工作:

audioEl.src = "https://www.kasandbox.org/programming-sounds/rpg/giant-no.mp3"; 

但不是這樣的:

audioEl.src = ohnoesEl.href; 

回答

1

我喜剛剛測試過你的代碼,結果發現href工作得很好很好。

<a id="a1" href="https://www.google.ca">Google</a> 
<button onclick="changeAudio(event)">Click Me</> 

<script> 
var a1 = document.getElementById('a1') 

function changeAudio(e){ 
    e.preventDefault() 
    var audio = document.createElement('audio') 
    audio.src = a1.href 
    document.body.appendChild(audio) 
} 
</script> 
相關問題