HTML5 音频播放器。无法更改 src 元素
HTML5 audio player. Cannot change the src element
我正在尝试动态更改 HTML 音频播放器的 src 值,但出于某种原因我无法更改它,它停留在它的占位符值上。
这是我的 HTML 元素:
<audio controls preload="none" style="width:480px;">
<source id="mp3" src="placeholder" type="audio/mp3" />
</audio>
这是我的 Javascript:
var tempMp3 = "http://www.someurl.org/somefile.mp3";
$("#mp3").attr("src", tempMp3);
有人知道我在这里犯了什么愚蠢的错误吗?
干杯
更改源后,请确保 运行 音频元素上的 .load()
函数加载更改。
示例(假设 id "audio" 设置为音频元素):
var tempMp3 = "http://www.someurl.org/somefile.mp3";
$("#mp3").attr("src", tempMp3);
$("#audio").load();
$("#audio").play();
代码看起来不错,可能就像@Nick Dugger 所说的那样,您正在尝试更改尚未准备就绪的 DOM 元素
A page can't be manipulated safely until the document is "ready."
jQuery detects this state of readiness for you. Code included inside
$( document ).ready() will only run once the page Document Object
Model (DOM) is ready for JavaScript code to execute. Code included
inside $( window ).load(function() { ... }) will run once the entire
page (images or iframes), not just the DOM, is ready.
第一个选项
尝试将代码放入此 $(document).ready()
$( document ).ready(function() {
var tempMp3 = "http://www.someurl.org/somefile.mp3";
$("#mp3").attr("src", tempMp3);
});
第二个选项
另一种选择是将 <script>
标签放在 <body>
标签的末尾
尝试一些简单的 JavaScript:
var audio=document.getElementById("my_audio_element");
audio.src="source.mp3";
audio.play();
这对我有用。 HTML5 音频仍然有点不稳定,并且在所有主要浏览器中的实现方式不尽相同。如果你想让它在手机上播放,那就更难了。不过,您的代码对我来说看起来不错。希望这对您有所帮助!
我正在尝试动态更改 HTML 音频播放器的 src 值,但出于某种原因我无法更改它,它停留在它的占位符值上。 这是我的 HTML 元素:
<audio controls preload="none" style="width:480px;">
<source id="mp3" src="placeholder" type="audio/mp3" />
</audio>
这是我的 Javascript:
var tempMp3 = "http://www.someurl.org/somefile.mp3";
$("#mp3").attr("src", tempMp3);
有人知道我在这里犯了什么愚蠢的错误吗?
干杯
更改源后,请确保 运行 音频元素上的 .load()
函数加载更改。
示例(假设 id "audio" 设置为音频元素):
var tempMp3 = "http://www.someurl.org/somefile.mp3";
$("#mp3").attr("src", tempMp3);
$("#audio").load();
$("#audio").play();
代码看起来不错,可能就像@Nick Dugger 所说的那样,您正在尝试更改尚未准备就绪的 DOM 元素
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.
第一个选项
尝试将代码放入此 $(document).ready()
$( document ).ready(function() {
var tempMp3 = "http://www.someurl.org/somefile.mp3";
$("#mp3").attr("src", tempMp3);
});
第二个选项
另一种选择是将 <script>
标签放在 <body>
标签的末尾
尝试一些简单的 JavaScript:
var audio=document.getElementById("my_audio_element");
audio.src="source.mp3";
audio.play();
这对我有用。 HTML5 音频仍然有点不稳定,并且在所有主要浏览器中的实现方式不尽相同。如果你想让它在手机上播放,那就更难了。不过,您的代码对我来说看起来不错。希望这对您有所帮助!