Javascript 为什么引导typeahead对具有相同ID的输入元素不起作用?
我的HTML结构如下所示:Javascript 为什么引导typeahead对具有相同ID的输入元素不起作用?,javascript,twitter-bootstrap,Javascript,Twitter Bootstrap,我的HTML结构如下所示: <div class="controls"> <input id="car" class="span3" type="text" placeholder="B.E" autocomplete="off" value="" name="car[]"> </div> <div class="controls"> <input id="car" class="span3" type="text" placehold
<div class="controls">
<input id="car" class="span3" type="text" placeholder="B.E" autocomplete="off" value="" name="car[]">
</div>
<div class="controls">
<input id="car" class="span3" type="text" placeholder="B.E" autocomplete="off" value="" name="car[]">
</div>
getcar()
是使用ajax
它仅为第一个输入
元素而不是第二个输入
元素显示typeahead
我现在该怎么办?同一个ID不能使用两次。尝试以下方法(未经测试,但您应该了解):
有几点可能会导致您的问题 Ajax调用 通过调用
data=getData(),无法从ajax请求中获取数据代码>
您必须使用回调,您可以在
重复ID
同一页面上的HTML元素ID必须不同。检查一下。相反,您可以使用类,如我有一个动态DOM,因此,我使用:
对于每个新元素,我都会给出一个随机id,然后根据id在该元素上激活typeahead
$( "body" ).on( "click", ".typeahead", function() {
if( $(this).data('autocomple_ready') != 'ok' ){
$(this).attr('id',Math.round(new Date().getTime() +(Math.random() * 100)));
var assigned_id=$(this).attr('id');
$('#'+assigned_id).typeahead({
hint: true,
highlight: true,
minLength: 4,
delay:500,
source: function (query, process) {
return $.post('put_your_url_here',{ 'query': query },
function (data) {
return process(data);
},'json');
},
displayText: function(item){ return item.name;}
});
};
$(this).data('autocomple_ready','ok');
});
首先也是最重要的是,你不能有两个元素具有相同的ID,ever.ID:唯一标识一个事物的方法。因此,如果你不止一次(在任何事情中)使用同一个ID,它都会出现可怕的错误。事实上,我在上面动态生成input
元素。如果我将input
元素ID生成为car[]
,那么我应该如何编写javascript来生成源数据?是否可以取消tyeahead插件的初始化,或者以某种方式更改源的内容..?环顾四周,就像或,但它已经得到了回答。
<div class="controls">
<input id="car1" class="typeahead span3" type="text" placeholder="B.E" autocomplete="off" value="" name="car[]">
</div>
<div class="controls">
<input id="car2" class="typeahead span3" type="text" placeholder="B.E" autocomplete="off" value="" name="car[]">
</div>
car = getcar();
$(".typeahead").click(function() {
$('.typeahead').typeahead({
source: $(this),
items: 10
});
});
$( "body" ).on( "click", ".typeahead", function() {
if( $(this).data('autocomple_ready') != 'ok' ){
$(this).attr('id',Math.round(new Date().getTime() +(Math.random() * 100)));
var assigned_id=$(this).attr('id');
$('#'+assigned_id).typeahead({
hint: true,
highlight: true,
minLength: 4,
delay:500,
source: function (query, process) {
return $.post('put_your_url_here',{ 'query': query },
function (data) {
return process(data);
},'json');
},
displayText: function(item){ return item.name;}
});
};
$(this).data('autocomple_ready','ok');
});