Twitter bootstrap typeahead unable to add to dynamically created element

别来无恙 提交于 2019-12-01 17:54:28

问题


Is there a way to convert twitter bootstrap's typeahead function into a $("body").on() function? The following code works fine if the element exists on the page load.

$("#job_title").typeahead({
    source: searchFunction,        
    onselect: function(obj) {            
    }
});

But if I add the text input with id="job_title" dynamically, the above function doesn't work. Is there a workaround for this?


回答1:


This solution requires no additional javascript. From https://stackoverflow.com/a/15094730

$("#element-that-will-contain-typeaheads").on("DOMNodeInserted", function () {
    $(this).find(".typeahead").typeahead();
});



回答2:


I downloaded jquery.livequery.js to get the behavior I wanted:

$("#job_title").livequery("create", function() {
    $(this).typeahead({
        source: searchFunction,        
        onselect: function(obj) {            
        }
    });
});



回答3:


var fx = {
    "init":function() {
        $("#id_of_an_element").typeahead({
            minLength:2,
            delay:1 ...
        })
    },
    "method2":function(){
        some content;
    }
}

Every time the element containing the typeahead is loaded into the DOM (eg. via AJAX success, call fx.init();



来源:https://stackoverflow.com/questions/11037322/twitter-bootstrap-typeahead-unable-to-add-to-dynamically-created-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!