因此,经过数小时的艰苦努力,我做了一个 JS hack 来解决问题:
function lockComboBox ($aComboBox, aNullLabel) {
// TODO: Add the ability to not have a null option...?
// Set nullOption if it's not.
if (aNullLabel == null || aNullLabel == '') {
aNullLabel = 'None';
}
$aComboBox.jqxComboBox('insertAt', { label: aNullLabel, value: ''}, 0);
$aComboBox.jqxComboBox({autoComplete: true });
$aComboBox.on('focusout', function (eventargs) {
var $this = $(this);
// Items are all items, visible items is the set after filtering during autocompletion.
var items = $this.jqxComboBox('getItems');
var vItems = $this.jqxComboBox('getVisibleItems');
// Function to check for 'None' and null out the value if found.
// Necessary because the combo box will stick the label as the value if the value is null.
function nullFix (nameAttrib) {
if ($this.jqxComboBox('val') == aNullLabel) {
$this.find("input[name^='"+nameAttrib+"']").val('');
return;
}
}
// Next check to see if the value is 'None'
var valueMember = $this.jqxComboBox('valueMember');
nullFix(valueMember);
// Next check to see if the value is an exact match to one of our items
var valueMember = $this.jqxComboBox('valueMember');
var value = $this.find("input[name^='"+valueMember+"']").attr("value");
for (var i = 0; i < items.length; i++) {
if (value == items[i].value) {
$this.jqxComboBox('close');
$this.jqxComboBox('selectIndex', items[i].index);
return;
}
}
// Next see if the visible items are less than the total
if (vItems.length < items.length && vItems.length > 0) {
// If that's the case, it's been filtered, so take the closest one.
$this.jqxComboBox('close');
$this.jqxComboBox('selectItem', vItems[0]);
// Perform another nullcheck
nullFix(valueMember);
} else {
// Otherwise, clear the selection
$this.jqxComboBox('close');
$this.jqxComboBox('clearSelection');
}
});
}
这就是诀窍。制作您的组合框,然后在其上调用函数,如下所示:
// Create a jqxComboBox with the data adapter
$comboBox.jqxComboBox({ source: myAdapter, displayMember: "displayLabels", valueMember: "actualValues", width: 200, height: 25 });
// Lock the combo box to its own values, with null option 'None'
lockComboBox ($comboBox, 'None');
它似乎可以正确处理可能发生的不同情况:框失去焦点,或用户从下拉列表中进行选择等。没有“无”项,我无法修复一个行为怪癖(可能很难清除该框)所以我添加了它。我可能需要稍后添加一些内容,以便您可以将其锁定为值,但没有 null 选项。
我希望这对以后的人有用。 :)
编辑:
这实际上是有问题的;当您第一次选择某些东西时,它似乎可以工作,但是如果您再次聚焦/模糊该字段,它会由于某种原因使其空白。我不会解决这个问题,因为现在接受的答案中有一个更简单的解决方案。