【问题标题】:Dynamic input textbox not binding to autocomplete动态输入文本框未绑定到自动完成
【发布时间】:2011-10-21 22:54:35
【问题描述】:

我正在尝试遵循此解决方案,但没有得到任何运气。 jQuery autocomplete for dynamically created inputs

var autocomp_opt = {
    source: function (request, response) {

    $.ajax({
        url: "ServiceProxy.asmx/ByKeyWord",
        cache: false,
        data: "{ 'term':'" + request.term + "'}",
        dataType: "json",
        type: "POST",
        crossDomain: "true",
        contentType: "application/json; charset=utf-8",
        error: function (xhr, textStatus, errorThrown) {
            alert('Error: ' + xhr.responseText);
        },
        success: function (data) {
            response($.map(data, function (item) {
                return item.split(",");
            }));       
        },

        error: function (a, b, c) {

        }
    });
},
    minLength: 2
};

然后当我的输入框生成时,我尝试了......

    input = document.createElement("input");
    input.disabled = true;  
    input.className = this.FORM_INPUT_CLASS;

    $(input.id).autocomplete(autocomp_opt);
    table.rows[table.rows.length - 1].cells[1].appendChild(input);

没有错误,但似乎没有正确绑定它...如果有人有任何想法,请发布。谢谢。

【问题讨论】:

  • 检查浏览器的 JavaScript 控制台。你最终会得到input.id 没有被定义,很可能。
  • 为什么不用append和live jquey函数?
  • input.id 在别处定义并且显示正确。你能举一个自动完成的例子吗?我看到的示例与鼠标单击有关。但是 did 只是一个预定义的函数,所以我不确定。 jquery 语法快把我逼死了……
  • input.id的值是多少?
  • 对不起 - 我应该更清楚。它只是文本框的 id="myvalue" 的名称,设置为 input.id = "myvalue"

标签: javascript jquery jquery-ui autocomplete jquery-autocomplete


【解决方案1】:

尝试更改此行:

$(input.id).autocomplete(autocomp_opt);

到这里:

$('#' + input.id).autocomplete(autocomp_opt);

【讨论】:

  • 看到这个让我发笑,我经常犯这个错误。由于 input.id 没有哈希符号,jQuery 只是不返回任何元素,并跳过绑定并优雅地失败而没有错误,仅仅是因为它找不到预期的目标。
  • @jk 那没用。当输入文本已经在页面上时,它可以工作。但不能动态工作...
【解决方案2】:

当我添加时它工作:

    $('#fieldname").autocomplete(autocomp_opt);

在这行之后

    table.rows[table.rows.length - 1].cells[1].appendChild(input);

我猜它只能在输入框附加到某些东西时才能注册。还值得注意的是,添加某种事件句柄onfocus,onselect,即..,它也有效。虽然我怀疑,这是因为此时输入框已完全渲染/添加。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    相关资源
    最近更新 更多