我正在尝试使用 bootstraps typeahead 作为用户的灵活选择。因此,如果该项目是已知的,他们会选择它,如果不是,则会打开一个对话框,允许他们输入一个新项目。
我通过观察输入上的更改事件来做到这一点,如果输入 val 不在源数组中(对于预输入),则向用户显示“添加项目”对话框。问题是,如果用户单击选项之一,则在预先输入有机会设置 val 之前发送更改事件。这是因为单击会导致文本模糊。
我想检查活动元素以解决此问题,因此在更改事件中查看 document.activeElement 并查看它是否是 typeahead 选项之一,这不起作用并返回了整个 body 元素。
这是代码的精简版本:
html
<div id="contactModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Unknown Contact</h3>
</div>
<div class="modal-body">
<p>The contact you have entered is unknown. Press cancel to enter a different contact or fill out the details below to create a new contact</p>
<label>Name</label>
<input id="modal_contact" type="text" placeholder="dealership contact" value=""/>
<label>Email</label>
<input id="modal_contact_email" type="text" placeholder="dealership contact" value=""/>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button id="save" class="btn btn-primary">Save changes</button>
</div>
</div>
Javascript
var contacts = ['pete','geoff'];
$('.typeahead').typeahead({source:contacts, updater : function(item){
console.log('updater fired'); //fires after first change event
return item;
}});
$('input').change(function(ev){
console.log($(ev.target).val());
if ($.inArray($(ev.target).val(), contacts) < 0)
$('#contactModal').modal();
})
还有一个 JSFiddle 版本http://jsfiddle.net/k39vM/
有谁知道我如何测试用户是否点击了一个提前输入来确定这是否导致了更改事件?