Javascript - 按钮选择和取消选择
我的 HTML 中有以下一些按钮:
<p>
<input class="answerBtns" name="answer" type="button" value="A" />
<input class="answerBtns" name="answer" type="button" value="B" />
<input class="answerBtns" name="answer" type="button" value="C" />
<input class="answerBtns" name="answer" type="button" value="D" />
<input class="answerBtns" name="answer" type="button" value="E" />
</p>
我想知道的是,例如,如果我希望用户选择 3 个按钮,那么如果用户单击一个按钮,它将以某种颜色突出显示该按钮(假设为绿色)但用户只能选择三个按钮。如果单击其他按钮,则不会选择该按钮。仅当用户取消选择所选按钮然后选择他想要的按钮时才可以选择附加按钮。这意味着最多只能选择 3 个按钮。
我的问题是 Javacsript 中的哪些函数可以用来做到这一点?
谢谢
I have some buttons below in my HTML:
<p>
<input class="answerBtns" name="answer" type="button" value="A" />
<input class="answerBtns" name="answer" type="button" value="B" />
<input class="answerBtns" name="answer" type="button" value="C" />
<input class="answerBtns" name="answer" type="button" value="D" />
<input class="answerBtns" name="answer" type="button" value="E" />
</p>
What I want to know if lets say I want the user to select 3 buttons for example, then if the user clicks on a button, it will highlight the button in a color (lets say green) but the user can only have three buttons selected. If an additional button is clicked then that button would not be selected. The additional button can only be selected if the user unselects a selected button and then selects the button he wishes. This means that only 3 buttons can be selected at maximum.
My question is that what functions in Javacsript can be used to be able to do this?
Thank You
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您必须为按钮指定不同的名称。
我建议是使用jquery将按钮的类更改为answerBtnsSelected之类的内容,当选择按钮时,这也将帮助您使用CSS样式来突出显示按钮。
然后您可以做的是创建一个函数来检查该类的按钮数量,如果是三个或更多,则忽略或其他,否则更改类以使其被选中。
添加了取消选择按钮的逻辑
Firstly, you have to give your buttons different names.
What I would suggest is using jquery to change the class of the button to something like answerBtnsSelected when a button is selected this, will also help you with your css styles to highlight the button.
What you can then do is create a function that checks the amount of buttons with that class, and if it's three or more then ignore or whatever, else change the class to make it selected.
Added logic to unselect button