【问题标题】:using javascript to generate an id to be an 'active state'使用 javascript 生成一个 id 为“活动状态”
【发布时间】:2015-11-10 18:16:09
【问题描述】:

希望有人可以提供帮助。

我有一个包含 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();
 });

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    您可以使用.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
    });
    

    【讨论】:

    • 为什么不一次选择所有按钮,而不是重复相同的代码 4 次?
    • 谢谢,这对我添加“活动”类肯定有用,但是现在单击每个阶段不会做任何事情(除了添加类)。有更多代码可能与之冲突,我已经更新了我的原始帖子。
    • @DesBank,上面的代码只是为了管理这个类,你需要把这个事件处理程序添加到你现有的代码中
    • 感谢 Satpal。活动状态和功能运行良好。理想的一件事是,当页面加载时,第一阶段是否可以作为“活动”类加载?在您开始点击之前,活动状态不会生效。
    • @DesBank 只需使用$("#first").trigger('click')
    猜你喜欢
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多