任何在这里寻找Knockout JS集成的人。
给定以下HTML(“标准引导程序”下拉按钮):
<div class="dropdown">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Select an item
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>
<a href="javascript:;" data-bind="click: clickTest">Click 1</a>
</li>
<li>
<a href="javascript:;" data-bind="click: clickTest">Click 2</a>
</li>
<li>
<a href="javascript:;" data-bind="click: clickTest">Click 3</a>
</li>
</ul>
</div>
使用以下JS:
var viewModel = function(){
var self = this;
self.clickTest = function(){
alert("I've been clicked!");
}
};
对于那些希望基于可剔除可观察数组生成下拉选项的人,代码将类似于:
var viewModel = function(){
var self = this;
self.dropdownOptions = ko.observableArray([
{ id: 1, label: "Click 1" },
{ id: 2, label: "Click 2" },
{ id: 3, label: "Click 3" }
])
self.clickTest = function(item){
alert("Item with id:" + item.id + " was clicked!");
}
};
<!-- REST OF DD CODE -->
<ul class="dropdown-menu" role="menu">
<li>
<a href="javascript:;" data-bind="click: $parent.clickTest, text: option.clickTest"></a>
</li>
</ul>
<!-- REST OF DD CODE -->
注意,可观察数组项隐式传递到click函数处理程序中,以在视图模型代码中使用。