单击时替换按钮颜色

时间:2018-03-19 05:07:48

标签: javascript php jquery html

我已经生成了一个按钮列表,并且希望每个按钮在单击时单独更改颜色,因此每次单击时它们会交替变为红色/绿色。

<?php
$getInfo = getAllRows();

$button = '<button type="button" id ="toggle" ></button>';?>


</php>
<html>
<div class ="enableButtons">
//there are 5 values to iterate over
<?php foreach ($getInfo):
echo $button;
?>
<?php endforeach ?>

                 </div>
 </html>

<script>
$('#toggle').click(function(){
  $(this).toggleClass('green');

});

</script>

.green
{
    background-color:green;
}

我遇到的问题是,只有第一个按钮似乎是翻转颜色,其他人在我点击时什么都不做!我也不确定如何从红色/绿色交替切换。

任何帮助都会是很棒的欢呼!

3 个答案:

答案 0 :(得分:2)

问题在于id。似乎所有按钮都具有相同的id,这是错误的标记。

尝试将id替换为公共类

$button = '<button type="button" class="someCommonCLass" ></button>'

在js

$('.someCommonCLass').click(function(){
  $(this).toggleClass('green');

});

答案 1 :(得分:1)

Here's a JSFiddle。与其他人建议的一样,您希望使用class而不是id输出按钮,以便使用jQuery更轻松地选择按钮。这是一个很好的CSS的例子。你的按钮格式应该是这样的。

<button type="button" class="toggle"> label </button>

这是一个有效的SO片段。

$('.toggle').click(function(){
  $(this).toggleClass('green');

});
.toggle {
    background-color:#df0606;
    padding:7px;
    border:1px solid red;
    color:white;
    font-size:1.18em;
    box-shadow:2px 4px black;
    margin-left:4px;
    margin-right:4px;
}
.toggle:hover {
    background-color:#cd0101;
    padding:7px;
    border:1px solid red;
    color:#ff2a31;
    font-size:1.18em;
    box-shadow:2px 4px #510809;
    margin-left:4px;
    margin-right:4px;
}

.green {
    color:white;
    padding:7px;
    border:1px solid lime;
    background-color:green;
    font-size:1.18em;
    box-shadow:2px 4px black;
    margin-left:4px;
    margin-right:4px;
}
.green:hover {
    color:lime;
    padding:7px;
    border:1px solid lime;
    background-color:#12de09;
    font-size:1.18em;
    box-shadow:2px 4px #044f12;
    margin-left:4px;
    margin-right:4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<p>
These buttons generated with PHP:
</p>
<div class ="enableButtons">
    <button type="button" class="toggle">One</button>
    <button type="button" class="toggle">Two</button>
    <button type="button" class="toggle">Three</button>
</div>
<p>
Here's some text. Text text text.
</p>
</body>
</html>

答案 2 :(得分:0)

在生成按钮列表时,应该使用类而不是id 试试这个:

$button = '<button type="button" class ="toggle" ></button>'
<script>
 $('.toggle').click(function(){
  $(this).toggleClass('green');
 });

</script>
相关问题