简体   繁体   English

addEventListener 和 if 按钮上的语句被点击

[英]addEventListener and if statement on button clicked

I am new to coding and here I am trying to use addEventListener and if statement to change the color of the box when button clicked, but I am not doing it the right way and not managing to find the proper way online.我是编码新手,在这里我尝试使用 addEventListener 和 if 语句来在单击按钮时更改框的颜色,但我没有以正确的方式进行操作,也没有设法在线找到正确的方法。

var box = document.getElementById("box");
var yes = document.getElementById("yes");
var no  = document.getElementById("no");
yes.addEventListener("click", function(){
    if (yes.clicked == true){
        box.style.backgroundColor = "red";        
    } if(no.clicked == true) {
        box.style.backgroundColor = "green";
    }
});

You are only aplying a listener to the button yes, so your listener only will works for your yes button:您只是将监听器应用于按钮 yes,因此您的监听器仅适用于您的 yes 按钮:

//Listener attached only to yes
yes.addEventListener("click", function(){
    if (yes.clicked == true){
        box.style.backgroundColor = "red";        
    } if(no.clicked == true) {
        box.style.backgroundColor = "green";
    }
});

So you don't need an if statement for your purpose, you only need various listeners:所以你不需要 if 语句来达到你的目的,你只需要各种监听器:

box.addEventListener("click", function(){
     alert("box clicked!");
});

yes.addEventListener("click", function(){
     box.style.backgroundColor = "red";
)};

no.addEventListener("click", function(){
     box.style.backgroundColor = "green";
});

And if your buttons are inside the box you can do this instead of the upper functionality:如果你的按钮在盒子里,你可以这样做而不是上面的功能:

box.addEventListener("click", function(ev){

    if(ev.currentTarget.id == "yes"){
        box.style.backgroundColor = "red";
    }else if(ev.currentTarget.id == "no"){
        box.style.backgroundColor = "green";
    }

});

When you add an event listener to the yes button, it will only trigger when the yes button is clicked.当你给yes按钮添加事件监听器时,它只会在yes按钮被点击时触发。 Therefore, you need a separate one for both buttons and no if statement is necessary.因此,两个按钮都需要一个单独的按钮,并且不需要 if 语句。

var box = document.getElementById("box");
var yes = document.getElementById("yes");
var no  = document.getElementById("no");
yes.addEventListener("click", function(){
        box.style.backgroundColor = "green";        
});
no.addEventListener("click", function(){
        box.style.backgroundColor = "red";        
});
function colorChange(e) {
    if(e.target.id == 'yes'){ // if user clicked the yes button
        box.style.backgroundColor = "red";

    }else if(e.target.id == 'no'){ // if user clicked the no button
        box.style.backgroundColor = "green";
    }
}
yes.addEventListener('click', colorChange);
no.addEventListener('click', colorChange);

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

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