如何在typeahead中选择元素时如何创建div?

时间:2016-04-27 19:34:40

标签: javascript jquery html typeahead

这是我的功能:

$('input.typeahead').bind('typeahead:selected', function (obj, datum, name){
     alert(JSON.stringify(obj)); // object
     // outputs, e.g., {"type":"typeahead:selected","timeStamp":1371822938628,"jQuery19105037956037711017":true,"isTrigger":true,"namespace":"","namespace_re":null,"target":{"jQuery19105037956037711017":46},"delegateTarget":{"jQuery19105037956037711017":46},"currentTarget":
     alert(JSON.stringify(datum)); // contains datum value, tokens and custom fields
     // outputs, e.g., {"redirect_url":"http://localhost/test/topic/test_topic","image_url":"http://localhost/test/upload/images/t_FWnYhhqd.jpg","description":"A test description","value":"A test value","tokens":["A","test","value"]}
     // in this case I created custom fields called 'redirect_url', 'image_url', 'description'
     alert(JSON.stringify(name)); // contains dataset name
     // outputs, e.g., "my_dataset"
});

我希望能够在点击建议时创建div,但我无法弄明白。我怎样才能做到这一点?我试图附加一个onclick事件,但它甚至没有被调用。 任何帮助都非常感谢:)

1 个答案:

答案 0 :(得分:1)

您可以使用以下语法创建div元素并在输入后注入它:

$('input.typeahead').bind('typeahead:selected', function(obj, datum, name) {

    var $div = $('<div/>', {
        class: 'whatever'
    });

    $div.append('some text');

    //insert after input
    $(this).after($div);

    // or you can inject it into a specific element
    $('#elementId').append($div);
});