使引导下拉按钮级联

时间:2015-02-06 14:37:18

标签: jquery html ajax twitter-bootstrap

我在我的网页上添加了两个下拉框,如下所示,但我想让它们级联,然后将下拉按钮的值传递给一个函数。

<div class="btn-group">
   <button data-toggle="dropdown" class="btn btn-success dropdown-toggle">Success <span class="caret"></span></button>
      <ul class="dropdown-menu">
         <li><a href="#" onClick="return false;">Action</a></li>
         <li><a href="#" onClick="return false;">Another action</a></li>
         <li><a href="#" onClick="return false;">Something else here</a></li>
         <li class="divider"></li>
         <li><a href="#" onClick="return false;">Separated link</a></li>
      </ul>
</div><!-- /btn-group -->
<div class="btn-group">
   <button data-toggle="dropdown" class="btn btn-info dropdown-toggle">Info <span class="caret"></span></button>
      <ul class="dropdown-menu">
         <li><a href="#" onClick="return false;">Action</a></li>
         <li><a href="#" onClick="return false;">Another action</a></li>
         <li><a href="#" onClick="return false;">Something else here</a></li>
         <li class="divider"></li>
         <li><a href="#" onClick="return false;">Separated link</a></li>
      </ul>
</div><!-- /btn-group -->

1 个答案:

答案 0 :(得分:5)

正如KyleT在评论中提到的那样,你可以使用枚举来代替数组。然而,作为一个舒适的选择,我将使用一个阵列。的 Fiddle

&#13;
&#13;
var states = [
    "Kansas",
    "Oklahoma",
    "Texas"    
];

$('.dropdown-menu > li > a').click(function() {
    yourFunction(this.text);
});

function yourFunction(val) {
        
    if ( val === "Action" ) {
        $('#states').html('');
        for ( var i in states ) {
            $('#states').append("<li><a href='#'>" + states[i] + "</a></li>");
        }
    }
    
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group">
  <button data-toggle="dropdown" class="btn btn-success dropdown-toggle">Success <span class="caret"></span>
  </button>
  <ul class="dropdown-menu">
    <li><a href="#">Action</a>
    </li>
    <li><a href="#">Another action</a>
    </li>
    <li><a href="#">Something else here</a>
    </li>
    <li class="divider"></li>
    <li><a href="#">Separated link</a>
    </li>
  </ul>
</div>
<!-- /btn-group -->
<div class="btn-group">
  <button data-toggle="dropdown" class="btn btn-info dropdown-toggle">Info <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" id="states">
    <li><a href="#">Action</a>
    </li>
    <li><a href="#">Another action</a>
    </li>
    <li><a href="#">Something else here</a>
    </li>
    <li class="divider"></li>
    <li><a href="#">Separated link</a>
    </li>
  </ul>
</div>
<!-- /btn-group -->
&#13;
&#13;
&#13;