简体   繁体   English

在Firefox中,onclick无法正常工作

[英]onclick does not work properly in firefox

I have a line of code that changes body background to black when particular img link is clicked, and if the img link is clicked again it returns to white. 我有一行代码可以在单击特定的img链接时将主体背景更改为黑色,如果再次单击img链接,它将返回为白色。 It works perfect in chrome, but in firefox it works for the first click but does not change back body background on second click. 它在chrome中可以完美运行,但是在Firefox中,它可以在第一次单击时使用,但在第二次单击时不会更改后身背景。 Here is the code: 这是代码:

HTML 的HTML

<a href="#" onclick="changeBackground('black');return false;"><img class="img1"  src="..."></img></a>  

JAVASCRIPT JAVASCRIPT

       <script type = "text/javascript">
            function changeBackground(color) {
                if(document.body.style.background != 'black'){
                localStorage.color = document.body.style.background = color;
                }
                else if(document.body.style.background === 'black'){
                localStorage.color = document.body.style.background = 'white';
                }           
                changeBackground(localStorage.color);
            };
      </script>  

I assume that this is not problem with onclick trigger because it works in firefox for the first click. 我认为onclick触发器不是问题,因为它可以在Firefox中用于首次单击。 It may be the javascript code..but I don't see anything missing... 可能是javascript代码..但我没有看到任何遗漏...

Your function is infinitely recursive, meaning that it calls itself endlessly with no way to break out of the loop. 您的函数是无限递归的,这意味着它无休止地调用自己,而没有脱离循环的可能。

I suggest moving your changeBackground() call outside of your function. 我建议将您的changeBackground()调用changeBackground()函数之外。

I also attached the call to window.onload so that the <body> styles will be available in the DOM before the function executes. 我还将调用附加到window.onload以便在函数执行之前<body>样式在DOM中可用。

I also loosened your if logic so that it's not reliant on backgroundColor initially being either "white" or "black". 我还放松了您的if逻辑,以使其不依赖于backgroundColor最初是“ white”或“ black”。

function changeBackground(color) {
    if (document.body.style.backgroundColor === 'black') {
        localStorage['color'] = 'white';
    } else {
        localStorage['color'] = color;
    }
    document.body.style.backgroundColor = localStorage['color'];
}

// this sets the background color to the localStorage value when the page loads
window.onload = function () {
    changeBackground(localStorage['color']);
}

WORKING EXAMPLE 工作实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM