Twitter Typeahead 不适用于动态创建的输入
Twitter Typeahead doesn't work with input created dynamically
我正在使用 Twitter Typeahead 为我的文本输入提供自动完成功能。
当我动态创建输入时,.typeahead()
不会显示提示 UI,除非在输入控件附加到 DOM 之后调用它。
这个有效:
var input1 = $('<input type="text" />');
$("#dynamic-container1").append(input1); /* (A) */
input1.typeahead(null, make_dataset()); /* (B) */
input1.focus();
这不是:
var input2 = $('<input type="text" />');
input2.typeahead(null, make_dataset()); /* (B) */
$("#dynamic-container2").append(input2); /* (A) */
input2.focus();
(注意标记为 (A)
和 (B)
的行的顺序。)
为什么会这样?在将输入附加到 DOM?
之前,是否有正确的方法来初始化 Typeahead
这是一个fiddle:http://jsfiddle.net/joz0fn3m/
您必须附加 input2.parent()
而不仅仅是 input2。因为 typeahead 不仅仅是那个输入元素,而是像下面这样的结构。通过仅附加输入,typeahead 缺少所需的结构。
<span class="twitter-typeahead">
<input type="text" class="tt-hint" readonly="" autocomplete="off" spellcheck="false" tabindex="-1" style="..." >
<input type="text" class="tt-input" autocomplete="off" spellcheck="false" dir="auto" style="...">
<pre aria-hidden="true" style="..."></pre>
<span class="tt-dropdown-menu" style="...">
<div class="tt-dataset-1">
</div>
</span>
</span>
这是更新后的 DEMO
希望对您有所帮助
我正在使用 Twitter Typeahead 为我的文本输入提供自动完成功能。
当我动态创建输入时,.typeahead()
不会显示提示 UI,除非在输入控件附加到 DOM 之后调用它。
这个有效:
var input1 = $('<input type="text" />');
$("#dynamic-container1").append(input1); /* (A) */
input1.typeahead(null, make_dataset()); /* (B) */
input1.focus();
这不是:
var input2 = $('<input type="text" />');
input2.typeahead(null, make_dataset()); /* (B) */
$("#dynamic-container2").append(input2); /* (A) */
input2.focus();
(注意标记为 (A)
和 (B)
的行的顺序。)
为什么会这样?在将输入附加到 DOM?
之前,是否有正确的方法来初始化 Typeahead这是一个fiddle:http://jsfiddle.net/joz0fn3m/
您必须附加 input2.parent()
而不仅仅是 input2。因为 typeahead 不仅仅是那个输入元素,而是像下面这样的结构。通过仅附加输入,typeahead 缺少所需的结构。
<span class="twitter-typeahead">
<input type="text" class="tt-hint" readonly="" autocomplete="off" spellcheck="false" tabindex="-1" style="..." >
<input type="text" class="tt-input" autocomplete="off" spellcheck="false" dir="auto" style="...">
<pre aria-hidden="true" style="..."></pre>
<span class="tt-dropdown-menu" style="...">
<div class="tt-dataset-1">
</div>
</span>
</span>
这是更新后的 DEMO
希望对您有所帮助