我有以下代码在两个音轨之间来回传递。但我觉得这两个功能可以简化为一个可以切换2个音轨的功能......
function addEventHandlers() {
$('a.next').toggle(function () {
tracka();
},
function () {
trackb();
});
}
function tracka() {
audio.trigger('pause');
audio.prop("currentTime", 0);
var mtrack = "ItstheMostWonderfulTimeoftheYear.mp3";
audio.prop("src", "audio/"+mtrack);
audio.trigger('play');
}
function trackb() {
audio.trigger('pause');
audio.prop("currentTime", 0);
var mtrack = "winterWonderland.mp3";
audio.prop("src", "audio/" + mtrack);
audio.trigger('play');
}
是否有更有效的方法将2个函数减少为单个函数?
答案 0 :(得分:0)
您可以随时切换src属性。你需要扩展jquery。
jQuery扩展程序:
$.fn.togglePropValue = function (name, vals) {
var toggles = vals.split(' ');
if (toggles.length > 1) {
if (this.prop(name) == toggles[0]) {
this.prop(name, toggles[1]);
} else if (this.prop(name) == toggles[1])
{
this.prop(name, toggles[0]);
}
}
return this;
}
<强>用法:强>
$('#toggleSong').click(function () {
$('#audio1').togglePropValue('src', 'http://www.stephaniequinn.com/Music/Commercial%20DEMO%20-%2007.mp3 http://www.stephaniequinn.com/Music/Commercial%20DEMO%20-%2009.mp3').trigger('play');
});