[英]Clicking on a different button doesn't allow me to click back on the original one
I created a jquery script which changes the css selector when I click on a specific button, well the script does work but I can't click back on the default selected button. 我创建了一个jquery脚本,当单击特定按钮时,该脚本会更改css选择器,该脚本可以正常工作,但无法单击默认的选定按钮。
I've tried changing a few variables and other things but nothing works. 我尝试更改一些变量和其他内容,但是没有任何效果。
$(document).ready(function() { $(".btn-secondary").click(function() { $(".btn-primary").addClass('btn-secondary').removeClass('btn-primary'); $(this).addClass('btn-primary').removeClass('btn-secondary'); }); });
.btn-primary { background-color: blue }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="col text-center"> <button class="btn mb-1 btn-primary" name="type" value="username">Username</button> <button class="btn mb-1 btn-secondary" name="type" value="email">Email</button> <button class="btn mb-1 btn-secondary" name="type" value="password">Password</button> <button class="btn mb-1 btn-secondary" name="type" value="hash">Hash</button> <button class="btn mb-1 btn-secondary" name="type" value="ip">IP Address</button> </div>
$(document).ready(function() {
$(".btn-secondary").click(function() {
$(".btn-primary").addClass('btn-secondary').removeClass('btn-primary');
$(this).addClass('btn-primary').removeClass('btn-secondary');
});
});
In line 2 here, you are only adding the click listener to the 4 buttons with that className and not the first button (the one you want to reclick) 在此处的第2行中,您仅将点击侦听器添加到具有该className的4个按钮中,而不是第一个按钮(要重新单击的按钮)中
I would suggest changing this: 我建议更改此:
$(".btn-secondary").click(function() {
To this: 对此:
$(".btn").click(function() {
Example Snippet: 示例片段:
$(document).ready(function() { $("#buttons .btn").click(function() { $(".btn-primary").addClass('btn-secondary').removeClass('btn-primary'); $(this).addClass('btn-primary').removeClass('btn-secondary'); }); });
.btn-primary { background-color: blue }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="buttons" class="col text-center"> <button class="btn mb-1 btn-primary" name="type" value="username">Username</button> <button class="btn mb-1 btn-secondary" name="type" value="email">Email</button> <button class="btn mb-1 btn-secondary" name="type" value="password">Password</button> <button class="btn mb-1 btn-secondary" name="type" value="hash">Hash</button> <button class="btn mb-1 btn-secondary" name="type" value="ip">IP Address</button> </div>
Final edit: added ID to div element to localize jQuery call (prevent unintended spillover to other parts of the project) 最终编辑:向div元素添加ID以本地化jQuery调用(防止意外溢出到项目的其他部分)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.