Javascript变量保留先前的值

时间:2019-06-17 15:48:34

标签: javascript html

    function myFunction() {

        var words = ["red", "green", "blue", "yellow"];

        var random;
        var getRandomWord = function () {
            random = Math.floor(Math.random() * words.length);

            return words[random];
        };


        var word = getRandomWord();
        document.getElementById(word).style.backgroundColor = word;
        var element = document.getElementById(word);

        setTimeout(function () { document.getElementById(word).style.backgroundColor = "white" }, 500);

        element.onclick = function () {

            alert('hh');
        }

每次执行此功能时,它都会生成一个随机的单词,它是元素的id。但是单词也保留以前生成的随机值。

这里是fiddle

2 个答案:

答案 0 :(得分:0)

您可以在设置颜色之前清除此颜色。

for(x=0; x<words.length; x++) {
    document.getElementById(words[x]).style.backgroundColor = "white" 
};

编辑:

好的,因此当颜色变为白色时,您需要清除onclick事件。

element.onclick更改为:

element.addEventListener('click', doAlert);

在myFunction之外放置一个新函数:

function doAlert() {
    alert('hh');
}

将setTimeout更改为:

setTimeout(function () { 
    document.getElementById(word).style.backgroundColor = "white";
    document.getElementById(word).removeEventListener('click', doAlert);
    }, 2000);

为了方便测试,我将超时时间更改为2秒。

并更改将其设置为白色的for循环:

for(x=0; x<words.length; x++) {
    document.getElementById(words[x]).style.backgroundColor = "white" 
    document.getElementById(words[x]).removeEventListener('click', doAlert);
};

现在可以确保在计时器用尽时清除它们,或者单击以显示一个新框。

答案 1 :(得分:0)

我理解这个问题,因为当我在代码沙箱中尝试您的代码时,由于变量字保留了先前生成的随机值,因此您的代码会生成先前的颜色:https://codesandbox.io/s/thirsty-leaf-ydxi4?fontsize=14

我发现一切正确,这个词有时会显示两次相同的颜色,因为您使用的是Math.random,这可能会生成两个相似的数字,而在使用Math.floor时会返回相同的Integer,类似

Math.floor(0.954322992037227 * 4) 

将导致

3

Math.floor(0.9053765386684278 * 4) 

将导致

3

您可以尝试不使用Math.random来解决该问题吗? https://codesandbox.io/s/compassionate-rhodes-n58om?fontsize=14

更新:我误解了这个问题,正如心理学家稍后在评论中所述:

  

按两次播放按钮(或直到出现两种不同的颜色)。我希望它仅在您单击最近生成的颜色时才发出警报,但是它也会在以前的彩色矩形上发出警报

通过为元素重新分配默认的onclick值解决了该问题, 这段代码可以解决问题:

  let elements = document.getElementsByClassName("rectAngle");
  for (let i = 0; i < elements.length; i++) {
   elements[i].onclick = function() {};
  }