cakephp div和按钮切换

时间:2017-03-24 04:50:33

标签: javascript jquery html cakephp

需要解决CakePHP和脚本问题

我使用三个按钮(让b1,b2& b3 )。三个按钮分别有自己独立的div( let d1,d2& d3 )。当我点击 b1 时, d1 应显示,但其他 d2& d3应该隐藏。当我点击 b2 时,应显示 d2 d3和d1 应隐藏。应该如何使用CakePHP和脚本来完成这项工作?

以下是我尝试的代码

  <button id="b1"> btn1 </button>
  <button id="b2"> btn1 </button>
  <button id="b3"> btn1 </button>

  <div id="d1" style="display:none"> this is div1 </div>
  <div id="d2" style="display:none"> this is div2 </div>
  <div id="d3" style="display:none"> this is div2 </div>

//这是脚本

<?php $this->Html->scriptStart(['block' => 'scriptBottom']); ?>
    (function($) {
        $(document).ready(function(){

        });


        $('#b1').click(function () {
         $('#d1').show();
         $('#d2').hide();
         $('#d3).hide();

        });


        $('#b2').click(function () {
         $('#d1').hide();
         $('#d2').show();
         $('#d3').hide();

        });

        $('#b3').click(function () {
         $('#d1').hide();
         $('#d2').hide();
         $('#d3').show();

        });
    }
    )( jQuery );

<?php $this->Html->scriptEnd(); ?>

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

$('button').click(function(){
      var index = $(this).index();//get the position of the current button 
      $('div').eq(index-1).show();// display the div corresponding to that position ,note: eq start counting from 0
      $('div').not(':eq('+(index-1)+')').hide();//hide the other usin not
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button> btn1 </button>
  <button> btn1 </button>
  <button> btn1 </button>

  <div style="display:none"> this is div1 </div>
  <div style="display:none"> this is div2 </div>
  <div style="display:none"> this is div3 </div>

使用ID:

$('button').click(function(){
    var id = '#d_'+this.id.split('_')[1];
    console.log(id);
    $(id).show();
    $('div').not(id).hide();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="b_1"> btn1 </button>
<button id="b_2"> btn1 </button>
<button id="b_3"> btn1 </button>

<div id="d_1" style="display:none"> this is div1 </div>
<div id="d_2" style="display:none"> this is div2 </div>
<div id="d_3" style="display:none"> this is div3 </div>