且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

事件监听器不工作?

更新时间:2021-11-17 21:51:03

如果您正在尝试收听活动,请点击,那么你需要这样的东西:

If you're trying to listen for an event click, then you need something like this:

 document.getElementById("BGchange").addEventListener("click", BGcolor);

然后,您需要修复此功能中的一些内容:

Then, you need to fix some things in this function:

function BGcolor (){
    var BG = BG2+1
    var BG2 = BG
    if(BG==0){
        document.body.style.background = white;
    } else if (BG==1) {
        document.body.style.background = black;
    }
}

因为你试图引用 BG2 在它被初始化之前所以不清楚你想在那里做什么。

Because you are trying to reference BG2 before it has been initialized so it is not clear what you want to be doing there.

按顺序,我改变的事情:

In order, the things I changed:


  1. 使用获取按钮的DOM元素document.getElementById()

  2. 使用 addEventListener()这是添加事件处理程序的标准方法

  3. 更改为单击单击按钮时创建的事件

  4. 仅将对事件处理程序的引用传递为 BGcolor 而不显示parens。你是立即调用它而不是传递对稍后可以调用的函数的引用。

  1. Get the DOM element for the button with document.getElementById()
  2. Use addEventListener() which is the standard way of adding event handlers
  3. Change to the click event which is what buttons create when you click on them
  4. Pass just a reference to the event handler as BGcolor without the parens. You were calling it immediately rather than passing a reference to the function that can be called later.

此外,还有很多东西要做修复你的 BGcolor()函数:

In addition, a bunch of things to fix in your BGcolor() function:


  1. 记住他们的状态的变量函数调用next必须在该函数之外声明。

  2. 颜色值是一个字符串,所以你要使用white,不是白色

  3. 要更改背景颜色,***使用 backgroundColor property。

  1. Variables that remember their state from one function call to the next must be declared outside that function.
  2. A color value is a string so you would use "white", not white.
  3. To change just the background color, it's best to use the backgroundColor property.

这是一个工作版本:

<button Id="BGchange">BUTTON!</button>
<script type="text/javascript">
document.getElementById("BGchange").addEventListener("click", BGcolor);

var curColor = "white";
function BGcolor (){
    if (curColor == "white") {
        curColor = "black";
    } else {
        curColor = "white";
    }
    document.body.style.backgroundColor = curColor;
}
</script>

工作演示: http://jsfiddle.net/jfriend00/Nk2N5/