javascript - 如果我手动更改选中状态,为什么我的 if 语句有效,但当我单击按钮时无效
问题描述
新来的,一个完整的 javascript 新手!
问题。我正在尝试制作钢琴,作为练习,我第一次真正尝试 javascript(也混合了一些 jQuery)。
但是为什么当我点击我的按钮时音频没有改变?如果我手动将选中状态删除/添加到 html 中的按钮,它会起作用,但不是“实时”。
有任何想法吗?我完全被难住了,我想这要么与存储在内存中的音频有关,要么我必须清除音频,但我不确定。任何帮助/建议将不胜感激。
谢谢
这是相关的代码位。和一个链接:
https://testing.jconnorgraphics.co.uk/pianjo/
function test() {
var C = document.getElementById("myAudioC");
var C3 = document.getElementById("myAudioC3");
if (document.getElementById('checked').checked){
$('.C').click(function() {
delete ('myAudioC3');
C.play();
C.currentTime = 0;
C.delete()
}
)
}
else {
$('.C').click(function() {
C3.play();
C3.currentTime = 0;
C3.delete()
}
)
};
};
test();
<div class="switch2" >
<label class="switch">
<input id="checked" type="checkbox" checked>
<span class="slider round"></span>
</label>
<p>Audio</p>
</div>
<div class="naturalkey C">
<p>C</p>
</div>
<audio id="myAudioC">
<source src="<?php echo get_template_directory_uri(); ?>/audio/piano/1 C.mp3" type="audio/mpeg">
</audio>
<audio id="myAudioC3">
<source src="<?php echo get_template_directory_uri(); ?>/audio/wavetable/2 C.mp3" type="audio/mpeg">
</audio>
哦,是的,我在 Wordpress 中创建它,因此是 php 位,但我认为它们与问题无关。
解决方案
这段代码会先设置.C
函数a的onclick事件,然后根据#checked
click事件动态设置.C
onclick事件。
$(document).ready(function(){
function a() {
delete ('myAudioC3');
C.play();
C.currentTime = 0;
C.delete()
}
function b() {
C3.play();
C3.currentTime = 0;
C3.delete()
}
$('#checked').click(function(){
let $this = $(this);
if($this.attr('checked')) {
$(".C").attr("onclick","a");
$this.attr('checked', false);
} else {
$(".C").attr("onclick","b");
$this.attr('checked',true)
}
});
$(".C").attr("onclick","a");
});