我有按钮和输入字段,单击按钮我想要聚焦输入字段也要清除字段值。任何想法?
请在下面注明我的html js
HTML:
<div class="inputStyle03">
<input type="text" data-bind="value: myParentViewModel.newCustomViewSubTab, hasFocus: true" id="inputCustomViewName" placeholder="Enter a name for your customer view" />
</div>
<div class="buttonStyle02 buttonStyle03Ext01 columnRight" data-bind="click: myParentViewModel.addNewCustomView">
<a>Add New Custom View</a>
</div>
JS:
function ParentViewModel()
{
var that = this;
that.myViewModelRibbon = new TabViewModel();
that.newCustomViewSubTab = ko.observable(); // newly adding custom view from input field
that.addNewCustomView = function (data, event) {
var allSubTAbs = data.myViewModelRibbon.ActiveSubTabs();
var userDefinedCustomView = {
"SubTabName": that.newCustomViewSubTab(), // getting the SubTabName from the input observables text box
"IconPath": "images/icons/Document.png",
"GroupID": "0",
"IsMultipleActive": "0",
"EnabledState": "enabled",
"CallbackOnSelect": "openCommonForm"
};
if (!!that.newCustomViewSubTab()) {
//if (that.newCustomViewSubTab() != null && that.newCustomViewSubTab() !== '') {
data.myViewModelRibbon.ActiveSubTabs.push(userDefinedCustomView);
} else {
alert("Please enter - Define a new custom view field");
};
}
return that;
}
var myParentViewModel = new ParentViewModel();
ko.applyBindings(myParentViewModel);
答案 0 :(得分:0)
清除可观察性很简单,你只需要用空值来调用它:
this.myValue = ko.observable('Initial Value');
// this will clear it
this.myValue('');
要设置焦点,可以将hasFocus
与保存值的布尔值observable结合使用。
运行以下代码段以查看其实际效果:
var viewModel = {
myValue: ko.observable('Initial Value'),
cleared: ko.observable(false),
clearValue: function() {
this.myValue('');
this.cleared(true);
}
};
ko.applyBindings(viewModel);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="text" data-bind="value: myValue, hasFocus: cleared" />
<input type="button" data-bind="click: clearValue" value="clear" />
&#13;