不同的按钮点击音频播放/暂停Jquery
问题描述:
这是一个简单的查询,但不知怎的,我似乎无法将手指放在似乎出错的地方。不同的按钮点击音频播放/暂停Jquery
我有两个按钮,即'问题'和'需要'。在点击前者时,音频文件1需要被播放,类似地,当稍后被点击时,音频文件1应该停止并且音频文件2被播放。这都是我为同一编写的代码是这样的:
var playing = false;
$("#problem").click(function(event) {
$("#audio").html('');
$("#audio").html('<source src="audio/expertise/file1.mp3" type="audio/mp3"><source src="audio/expertise/file1.wav" type="audio/x-wav"><source src="audio/expertise/file1.ogg" type="audio/ogg">');
playing = true;
});
$('.need_btn').attr('id', 'need_btn');
$("#need_btn").click(function(event) {
if (playing == true) {
$("#audio").trigger('pause');
playing = false;
if (playing == false){
$("#audio").attr('src','<source src="audio/expertise/file2.mp3" type="audio/mp3"><source src="audio/expertise/file2.wav" type="audio/x-wav"><source src="audio/expertise/file2.ogg" type="audio/ogg">');
$("#audio").trigger('play');
playing = true;
};
}
else{
/*$("#audio").trigger('play');*/
};
});
这工作正常播放文件1,第二个按钮被点击暂停文件1时,但不能播放的文件2. 我可以改变什么使它工作?
答
我觉得你的情况的问题是这段代码:
$("#audio").attr('src','<source src="audio/expertise/file2.mp3" type="audio/mp3"><source src="audio/expertise/file2.wav" type="audio/x-wav"><source src="audio/expertise/file2.ogg" type="audio/ogg">');
我只是通过official documentation去了,好像你是在一个不正确的方式使用.attr
。我还没有试过,我要发布的代码,但假设你想设置的source
元素的属性,你可能想尝试在这些线路上的东西:
$("source").attr({
src: "audio/expertise/file2.mp3",
type: "audio/mp3"
});
现在我明白了,你有.ogg
,.wav
和.mp3
版本。所以我认为你也可以像file1
那样直接为ID为“audio”的元素设置html
。我的建议是这样的:
$("#audio").html('<source src="audio/expertise/file2.mp3" type="audio/mp3"><source src="audio/expertise/file2.wav" type="audio/x-wav"><source src="audio/expertise/file2.ogg" type="audio/ogg">');
这将设置html
与所需标记对应的元素。我希望这能让你开始朝正确的方向发展。
感谢您分享帮助解决查询的.attr 的正确语法。 – Sajal 2014-10-27 08:02:02