Đối tượng source trong HTML DOM liên quan đến phần tử HTML <source>. Chúng ta có thể tạo và truy cập phần tử source bằng createElement() và getElementById().
Cú pháp
Cú pháp tạo đối tượng source:
var p = document.createElement("SOURCE");
Ví dụ
Ví dụ minh họa cho đối tượng source:
<!DOCTYPE html> <html> <body>
<h1>Ví dụ đối tượng source</h1>
<audio id="AUDIO_1" controls></audio>
<p>Thêm nguồn audio cho phần tử trên bằng cách nhấn nút dưới đây</p>
<button onclick="createSrc()">TẠO</button>
<p id="Sample"></p>
<script>
function createSrc() {
var s = document.createElement("SOURCE");
s.setAttribute("src", "sample.mp3");
s.setAttribute("type", "audio/mpeg");
document.getElementById("AUDIO_1").appendChild(s);
document.getElementById("Sample").innerHTML = "Điều khiển audio sẽ hoạt động bây giờ";
}
</script> </body> </html>
Kết quả
Khi nhấn nút "TẠO", phần tử source được thêm vào audio, trình phát audio hoạt động.
Giải thích ví dụ
Hàm createSrc() tạo phần tử SOURCE, thiết lập src="sample.mp3" và type="audio/mpeg", thêm vào audio element:
function createSrc() {
var s = document.createElement("SOURCE");
s.setAttribute("src", "sample.mp3");
s.setAttribute("type", "audio/mpeg");
document.getElementById("AUDIO_1").appendChild(s);
document.getElementById("Sample").innerHTML = "Điều khiển audio sẽ hoạt động bây giờ";
}