javascript试图解决这个问题的新手

时间:2014-09-25 19:38:10

标签: javascript jquery

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

我以为我可以将它变成一个函数,然后传递它的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/

2 个答案:

答案 0 :(得分:3)

一些事情。我不建议在事件发生后命名你的功能,尽管它仍然可以工作。您的代码的问题在于您立即调用该函数,并在函数中引用该参数。请改用:

&#13;
&#13;
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')
});
&#13;
.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;
}
&#13;
<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>
&#13;
&#13;
&#13;  

答案 1 :(得分:0)

修正:http://jsfiddle.net/0m9wos1r/4/

您需要解决的2个问题:

点击通话中的功能调用。像这样,使用匿名函数:

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

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

 $(e).addClass('active');
相关问题