使用相同的jQuery函数对不同的数据基于元素点击

Using same jQuery function on different data based on element clicked

本文关键字:于元素 元素 jQuery 函数 数据      更新时间:2023-09-26

我在codepen上创建了一个虚拟钢琴作为练习,我试图找到一种方法来编写一个jQuery函数,该函数将根据单击哪个键播放不同的声音。我将所有键创建为有序列表中的列表项,并根据它们是什么注释为每个键提供一个id。我已经弄清楚了如何根据按下的音符播放声音,从技术上讲,我可以复制每个音符的代码,但我想练习使我的代码更紧凑。这是我目前所看到的:

$('li')
    .mousedown(function(){
    $('#noteC')[0].play();
  })
    .mouseup(function(){
    $('#noteC')[0].pause(); 
    $('#noteC').prop('currentTime',0);
  })

我尝试添加var c = $('#noteC')[0]到脚本和<li class="ivory" id="C" data-note='c'>C</li>。我认为可能有一些方法可以通过将每个声音链接到它的列表项来触发它,这样当列表项被点击时,JS就知道要播放哪个声音。我怎样才能做到呢?

这里有很多选择,但有一个简单的方法:

为每个li添加一个数据属性,例如:data-note="noteC"

:

$('li').mousedown(function() {
   $('#'+$(this).data('note'))[0].play();
}).mouseup(function() {
   $('#'+$(this).data('note'))[0].pause();
   $('#'+$(this).data('note')).prop('currentTime',0);
});

编辑:根据你的data-note="c"属性,选择正确的注释,如:

$('#note'+$(this).data('note').toUpperCase()) //etc