knockout将项目绑定到bootstrap菜单

时间:2017-05-18 13:55:48

标签: javascript jquery css twitter-bootstrap knockout.js

我确信这对于经验丰富的淘汰赛用户来说很简单,但我不是。基本上我想创建一个表名数组,我想把它们放到一个引导按钮菜单中,当点击一个时我想抓住点击的值。目前我甚至无法将项目显示在按钮菜单中。我已经创造了一个我正在努力实现的点头之物:

https://jsfiddle.net/martin461/191arw3u/

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<div id="ko">
  <form>
    <div class="panel panel-default" style="padding: 15px 10px 0px 15px;" id="">
      <div class="form-group row">
        <label for="inputTable" class="col-lg-3 col-form-label">Select a Table to populate</label>
        <div class="controls form-inline">
          <div class="col-lg-6">
          </div>
          <button type="button" data-toggle="dropdown" class="btn btn-primary dropdown-toggle" style="min-width: 400px;">table of things <span class="caret"></span></button>
          <ul class="dropdown-menu scrollable-menu" style="min-width: 400px; margin-left:15px; max-height: 300px; height: auto; overflow-x: hidden;" role="menu" data-bind="foreach: Tables">
            <li>            
              <!-- to do <a role="menuitem" tabindex="-1" href="#" data-bind="text: tbl, click: getTableName"></a> -->
              <a role="menuitem" tabindex="-1" href="#" data-bind="text: tbl"></a>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </form>
</div>



$(function() {
  var main = new viewModel();

  ko.applyBindings(main, $('#ko')[0]);
});

function tabs(data) {
  this.tbl = ko.observable(data.tbl);
}

function viewModel() {
  var self = this;
  self.Tables = ko.observableArray();
  self.Tables.push(new tabs({tbl: "Bungle"}, {tbl: "Zippy"}));
  }
  //self.getTableName
  // alert show the table name!

干杯:)

1 个答案:

答案 0 :(得分:1)

$(function() {
  var main = new viewModel();
  ko.applyBindings(main, $('#ko')[0]);
});

function tabViewModel(data) {
  var self = this;
  self.Name = ko.observable(data);
  self.onClick = function(tab) {
    window.alert(self.Name());
  }
  return self;
}
function viewModel() {
  var self = this;
  self.Tables = ko.observableArray();
  self.Tables.push(new tabViewModel("Bungle"));
  self.Tables.push(new tabViewModel("Zippy"));
}

<div class="dropdown">
   <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
     <span class="caret"></span>
   </button>
   <ul class="dropdown-menu" data-bind="foreach: Tables">
     <li><a href="#" data-bind="text: Name, click: onClick"></a></li>
   </ul>
</div>

我为你更新了小提琴。

https://jsfiddle.net/191arw3u/12/