[英]Alternate button colour on click
我已经生成了一个按钮列表,希望每个按钮在单击时可以独立更改颜色,因此它们在每次单击时都会交替显示红色/绿色。
<?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;
}
我遇到的问题是,只有第一个按钮似乎在切换颜色,而当我单击时其他按钮什么也不做! 还不确定如何使其从红色/绿色交替切换。
任何帮助都将为您加油!
问题出在id
。 似乎所有按钮将具有相同的id
,这是错误的标记。
尝试用一个普通的类替换id
$button = '<button type="button" class="someCommonCLass" ></button>'
在js中
$('.someCommonCLass').click(function(){
$(this).toggleClass('green');
});
这是一个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>
在生成按钮列表时,应使用class而不是id
尝试以下操作:
$button = '<button type="button" class ="toggle" ></button>'
<script>
$('.toggle').click(function(){
$(this).toggleClass('green');
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.