Javascript 使用元素ID的JQuery选项卡

Javascript 使用元素ID的JQuery选项卡,javascript,jquery,html,tabs,Javascript,Jquery,Html,Tabs,我有两个按钮和两个带段落的div。我想创建选项卡,但我不知道在单击按钮时如何显示div。问题是我不能添加任何新的类或ID。我必须使用可用的类和ID。我正在寻找使用按钮和divid的解决方案 例如: 第一个按钮有ID“tab\u button\u one”,第一个div有ID input\u one。有没有一种方法可以通过使用“\u one”表单ID创建制表符切换 <button id="tab_button_one" class="btn active-button">Button

我有两个按钮和两个带段落的div。我想创建选项卡,但我不知道在单击按钮时如何显示div。问题是我不能添加任何新的类或ID。我必须使用可用的类和ID。我正在寻找使用按钮和divid的解决方案

例如:

第一个按钮有ID“tab\u button\u one”,第一个div有ID input\u one。有没有一种方法可以通过使用“\u one”表单ID创建制表符切换

<button id="tab_button_one" class="btn active-button">Button one</button>
<button id="tab_button_two" class="btn">Button two</button>

<div id="input_one" class="input active-input">
  <p>input one</p>
</div>

<div id="input_two" class="input">
  <p>input two</p>
</div>


<style>
.btn{
  background-color: transparent;
  border: 1px solid #000;
  padding: 10px;
  color: #000;
  cursor: pointer;
}

.btn.active-button{
  background-color: #0000b2;
  border-color: #0000b2;
  color: #fff;
}

.input{
  border: 1px solid #000;
  padding: 10px;
  margin: 10px 0;
  display: none;
}

.input.active-input{
  display: block;
}

</style>

<script>
  $('.btn').click(function(){
    if( $(this).hasClass('active-button') == false){
      var id = $(this).attr('id');
      $('.btn').removeClass('active-button');
      $(this).addClass('active-button');  
            $('.input').removeClass('active-input');
    }
  });
</script>
按钮一
按钮二
输入一

输入二

.btn{ 背景色:透明; 边框:1px实心#000; 填充:10px; 颜色:#000; 光标:指针; } .btn.active-button{ 背景色:#0000b2; 边框颜色:#0000b2; 颜色:#fff; } .输入{ 边框:1px实心#000; 填充:10px; 利润率:10px0; 显示:无; } .input.active-input{ 显示:块; } $('.btn')。单击(函数(){ if($(this).hasClass('active-button')==false){ var id=$(this.attr('id'); $('.btn').removeClass('active-button'); $(this.addClass('active-button'); $('.input').removeClass('active-input'); } });

假设ID始终遵循以下结构,您可以按照这些思路进行操作:

 $('.btn').click(function(){
    if( $(this).hasClass('active-button') == false){
      var id = $(this).attr('id').split('_')[2];
      $('.btn').removeClass('active-button');
      $(this).addClass('active-button');  
      $('.input').removeClass('active-input');
      $('#input_'+id).addClass('active-input');
    }
  });

这似乎与您对选项卡所做的操作一致。

是的,就是这样。非常感谢你。请您解释一下这部分代码:“.attr('id').split('u')[2];”?$(this).attr('id'))返回id属性的字符串,因为它的形式是“tab_按钮”[some id]”。我可以拆分字符串(使用带有“\u0”字符的string split()方法)。这给了我一个数组[“tab”,“button”,“some id]”,其中我对“[some id]”感兴趣,所以我取该数组的第三个元素(索引2)