我有一个带有大型淘汰视图模型的 .net webforms 页面,如果单击某些 div,我将切换一些 div 被隐藏或更改 css。我还有许多不同的事件处理程序和一些导致 ajax 查找的计算程序。
问题是当我在页面上的任何输入框中按 Enter 键时,viewmodel 中的一个函数会触发,该函数绑定到 div 上的单击处理程序,另一个绑定到此 div 内的按钮。如果我删除 div 上的点击绑定,整个页面都会被发布,这让我认为它与默认按钮行为有关。
我试图在这个jsfiddle和下面的代码中重新创建大部分功能,但是,这不是重新创建问题。
html
<body>
<div style="width:30%; float:left;">
<div id="div1" class="divClass" data-bind="click: showDiv1, css: { active: div1Visible }">
<h2>Div 1</h2>
</div>
<div id="div2" class="divClass" data-bind="click: showDiv2, css: { active: !div1Visible() }">
<h2>Div 2</h2>
<button id="randomButton">Random Button</button>
</div>
</div>
<div style="width:70%; float:left;" data-bind="visible: div1Visible">
<input placeholder="name"
id="nameSearch"
type="text"
name="nameSearch"
data-bind="value:nameSearch, valueUpdate: 'afterkeydown', event: {keyup: doSearch}"
autocomplete="off"
/>
<input placeholder="address"
id="addressSearch"
type="text"
name="addressSearch"
data-bind="value:addressSearch, valueUpdate: 'afterkeydown', event: {keyup: doSearch}"
autocomplete="off"
/>
<button id="resetButton">Reset</button>
<div>
<input id="grid" value="pretend I am a grid" />
</div>
</div>
<div style="width:70%; float:left;" data-bind="visible: !div1Visible()">
Should be hidden unless div 1 inactive
<div data-bind="text: message"></div>
</div>
</body>
js
function MyViewModel() {
// Data
var self = this;
self.div1Visible = ko.observable(true);
self.nameSearch = ko.observable('');
self.addressSearch = ko.observable('');
self.message = ko.observable('');
self.showDiv1 = function() {
self.div1Visible(true);
};
self.showDiv2 = function() {
self.div1Visible(false);
};
self.doSearch = function (data, event) {
var charCode = (event.which ? event.which : event.keyCode);
if (charCode === 40) {
$('#grid').focus();
}
return false;
};
self.quickSearch = ko.computed(function () {
if(self.nameSearch() || self.addressSearch()) {
//do some ajax grid binding if any values in search inputs
$('#grid').val('found values');
}
}, self).extend({ throttle: 400 });
self.searchHasValues = ko.computed(function () {
return self.nameSearch() || self.addressSearch();
});
self.setMessage = function() {
self.message('Shows when random button clicked');
};
self.resetSearch = function() {
self.nameSearch('');
self.addressSearch('');
$('#grid').val('searchReset');
};
}
window.viewModel = new MyViewModel();
ko.applyBindings(viewModel);
$('#randomButton').click(function (e) {
e.preventDefault();
viewModel.setMessage();
});
$('#resetButton').click(function (e) {
e.preventDefault();
viewModel.resetSearch();
});
css
.divClass {
background-color: #ccc;
height:200px;
padding:10px;
}
.active {
background-color: yellow;
}