你的代码做的是,它补充说,元素click事件侦听器,之后点击处理程序将不管你的x值的触发器,因为你没有任何检查内单击处理程序。
解决方法是只创建一次点击侦听器,并检查其中的值为x
。事情是这样的:
document.getElementById('a').onclick = function(){
if(x <= 1200 && x >= 600 && n == true) {
audio.play();
n = false;
}
}
看到这个(我已经更换了音频与格高亮玩,但它的原理相同):
var r = document.getElementById('r');
var n = true;
var x = 1000;
document.getElementById('a').onclick = function(){
if(x <= 1200 && x >= 600 && n == true) {
r.className = 'playing';
n = false;
printN();
setTimeout(function(){
r.className = '';
}, 2000);
}
}
function toggleN(){n = !n;printN()}
function printN(){document.getElementById('n').textContent = 'n is set to ' + n;}
function randomizeX(){x = Math.floor(Math.random() * 1200);printX()}
function printX(){document.getElementById('x').textContent = 'x equals ' + x;}
#r {display: inline-block; width: 50px; height: 50px; background: #ccc; transition: background 1s linear;}
#r.playing {background: green}
<button id="a">Hit me</button><br><br>
<div id="r"></div>
<p id="x">x equals 1000</p>
<p id="n">n is set to true</p>
<button onclick="toggleN()">Toggle n</button>
<button onclick="randomizeX()">Randomize x</button>
你是什么意思JQuery不适用于Chrome? – millerbr
除了millerbr的评论:jQuery在Chrome上运行得非常好。没有必要,无论如何,但它肯定有效。 –
@AMACB,它为什么重要 - OP说音频播放,甚至超过需要。 :) – Shomz