【问题标题】:Twitter Typeahead doesn't work with input created dynamicallyTwitter Typeahead 不适用于动态创建的输入
【发布时间】:2015-03-30 12:57:29
【问题描述】:

我正在使用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 是否有正确的方法?

这是一个小提琴:http://jsfiddle.net/joz0fn3m/

【问题讨论】:

    标签: jquery html typeahead.js twitter-typeahead


    【解决方案1】:

    您必须附加 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

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多