javascript新手试图弄清楚这一点

New to javascript trying to figure this out

本文关键字:弄清楚 这一点 新手 javascript      更新时间:2023-09-26

所以我试图在点击按钮时激活多个灯,但我不确定我做错了什么。

我想我可以把它做成一个函数,然后给它传递id名称,但看起来它没有按照我想要的方式运行。

html

<div class="lights">
    <div id="red"></div>
    <div id="yellow"></div>
    <div id="green"></div>
</div>
<div class="button">
    <button id="red_button"> Red Button </button>
    <button id="yellow_button">Yellow Button </button>
    <button id="green_button">Green Button </button>
</div>

css

.lights{
    height: 600px;
    width: 200px;
    background-color: black;
    padding-top: 15px;
}
.button{
    padding-top: 20px;
}
#red, 
#yellow,
#green {
    margin: 0 auto;
    background-color: black;
    border-radius: 50%;
    width: 180px;
    height: 180px;
    margin-top: 10px;
}
#red.active {
    background-color: red;
}
#yellow.active {
    background-color: yellow;
}
#green.active {
    background-color: green;
}

jquery

function click(e) { 
   $('#red,#yellow,#green').removeClass('active');
   $('e').addClass('active');
}
$('#red_button').click(click('#red'));
$('#yellow_button').click(click('#yellow'));
$('#green_button').click(click('#green'));

http://jsfiddle.net/0m9wos1r/1/

一些事情。我不建议以事件命名函数,尽管它应该仍然有效。代码的问题在于,您立即调用函数,并且在函数中引用了参数。使用这个替代:

function click(e) {
    $('#red,#yellow,#green').removeClass('active');
    $(e).addClass('active');
}
$('#red_button').click(function () {
    click('#red')
});
$('#yellow_button').click(function () {
    click('#yellow')
});
$('#green_button').click(function () {
    click('#green')
});
.lights {
    height: 600px;
    width: 200px;
    background-color: black;
    padding-top: 15px;
}
.button {
    padding-top: 20px;
}
#red, #yellow, #green {
    margin: 0 auto;
    background-color: black;
    border-radius: 50%;
    width: 180px;
    height: 180px;
    margin-top: 10px;
}
#red.active {
    background-color: red;
}
#yellow.active {
    background-color: yellow;
}
#green.active {
    background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="lights">
    <div id="red"></div>
    <div id="yellow"></div>
    <div id="green"></div>
</div>
<div class="button">
    <button id="red_button">Red Button</button>
    <button id="yellow_button">Yellow Button</button>
    <button id="green_button">Green Button</button>
</div>

已修复:http://jsfiddle.net/0m9wos1r/4/

需要解决的2个问题:

单击调用中的函数调用。像这样,使用匿名函数:

$('#red_button').click(function(){click('#red')});

单击功能中的选择器。像这样:

 $(e).addClass('active');