hover多个实例div时的独特声音

我正在尝试播放一个独特的声音,因为我将一个div元素hover在某个类( .trigger )上。 我的问题是,我有这个div类的多个实例,这意味着无论我hover哪个div,都会播放(相同)声音。

我的dreamcenario将是,只要下一个div徘徊(并希望下一个声音播放),任何先前的声音停止(我使用1-2秒长的声音文件)。

我已经通过html5将我的音频包含在div中我试图用作触发器。

我正在使用这个脚本:

 $(".trigger") $(this).each(function(i) { if (i != 0) { $("#sound") .clone() .attr("id", "sound" + i) .appendTo($(this).parent()); } $(this).data("cnt", i); }) $(this).mouseenter(function() { $("#sound" + $(this).data("cnt"))[0].play(); }); $("#sound").attr("id", "sound0"); 

我会因为任何帮助和更好的想法来实现这一点而感恩:我是一个可怕的新手 – 对不起。

就那么简单?

 $('.trigger').hover( function() { sound = $(this).children()[0]; sound.play(); }, function() { sound.pause(); sound.currentTime = 0; } ); 

现场演示: http //jsfiddle.net/oscarj24/VwSLj/5/

好的,你的第一个问题是你在每个div中都有相同的id(“声音”),而且id必须是唯一的。 我会把它改成一个类( class="sound" )然后,类似的东西

 $('.trigger').mouseenter(function() { $(".sound").get(0).pause(); $(this).find(".sound").get(0).play(); }); 

我没有测试过这段代码。

首先从ID更改为类,因为ID选择器不应该重复。

 

jQuery的

 $(".trigger").mouseenter(function () { var curAudio = $(this).find('audio'); var allAudio = $('.sound'); $.each(allAudio,function(ind,val){ $(this).get(0).pause(); $(this).get(0).currentTime = 0; }); curAudio.get(0).play(); }); 

在这里演示