javascript - 使用javascript生成一个id为 'active state'

标签 javascript jquery html

希望有人能帮忙。

我有一个包含 4 个部分的多阶段表单,并且任何时候都只显示一个部分。您可以通过单击四个按钮 1 到 4 中的任何一个来完成这些步骤。这些按钮的 html 在此过程中不会更改,我的问题:是否可以在 javascript 中添加任何内容,以便在阶段启动时生成一个类点击?例如

<p id="first" class="current"> 

让我有机会将其设置为事件状态

<小时/>

html 中的按钮是

<div>
  <p id="first"><span class="step">1</span><br /><br />Personal Details</p>
 <p id="second"><span class="step">2</span><br /><br />Quantity and Sizes</p>
 <p id="third"><span class="step">3</span><br /><br />Text, Cover and Finish</p>
 <p id="fourth"><span class="step">4</span><br /><br />Other</p>
 </div>

javascript 显示相关的 div 并隐藏其余部分

//relates to a prev next button at bottom of each stage
  $(document).ready(function(){
 $("#firstBtn").click(function(){
  if($("#loginForm").valid()){
     $("#firstStep").hide();
     $("#secondStep").show();
     }
 });
 $("#secondBtn").click(function(){
  if($("#loginForm").valid()){
     $("#thirdStep").show();
     $("#secondStep").hide();
     }
 });

 $("#thirdBtn").click(function(){
  if($("#loginForm").valid()){
     $("#fourthStep").show();
     $("#thirdStep").hide();
     }
 });

 $("#fourthBtnBack").click(function(){
  if($("#loginForm").valid()){
     $("#fourthStep").hide();
     $("#thirdStep").show();
     }
 });
 $("#thirdBtnBack").click(function(){
  if($("#loginForm").valid()){
     $("#thirdStep").hide();
     $("#secondStep").show();
     }
 });
 $("#secondBtnBack").click(function(){
  if($("#loginForm").valid()){
     $("#secondStep").hide();
     $("#firstStep").show();
     }
 });

// the 1,2,3,4 click between stages

$("#first").click(function(){
     $("#firstStep").show();
     $("#secondStep,#thirdStep,#fourthStep").hide();

 });
 $("#second").click(function(){
     $("#thirdStep,#firstStep,#fourthStep").hide();
     $("#secondStep").show();
 });

 $("#third").click(function(){
     $("#fourthStep,#firstStep,#secondStep").hide();
     $("#thirdStep").show();
 });
 $("#fourth").click(function(){
     $("#fourthStep").show();
     $("#thirdStep,#firstStep,#secondStep").hide();
 });

最佳答案

您可以使用.addClass().removeClass()

创建一个单独的点击处理程序来添加和删除类

$("#first,#secondStep,#thirdStep,#fourthStep").click(function(){
     $('.active').removeClass('active'); //Remove active class from other elements
     $(this).addClass('active'); //Add active class on current element
});

关于javascript - 使用javascript生成一个id为 'active state',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33627131/

相关文章:

javascript - Chartjs - 如何使线条位置垂直居中以及如何在背景中显示虚线?

javascript - for 循环中的 AJAX 调用不会将值返回到正确的数组位置

jquery - 无法将对象作为参数传递

jQuery 插件外部函数

javascript - 基于其位置的可拖动 DIV 样式

css - 如何在 JQM 1.4.2 中修改图标

c# - 有没有办法在 ASP.NET 面板控件上设置最小高度?

javascript - 按钮内的复选框?

javascript - 如何在 SimpleCart 中使用 paypal 快速结账?

javascript - 具有空值的多个属性的 Var