我有一个使用自动完成功能的输入字段。当我只这样做时,自动完成工作。但是:我想显示一个跨度,并在用户单击它时将其替换为输入框。不幸的是,自动完成功能中断了。考虑以下代码:
$(function () {
$('#my_span').live('click', function () {
var input = $('<input />', {'type': 'text', 'id': 'my_input', 'name': 'my_input', 'value': $(this).html()});
$(this).parent().append(input);
$(this).remove();
input.focus();
}
);
$('#my_input').live('blur', function () {
$(this).parent().append($('<span />' , {'id': 'my_span'}).html($(this).val()));
$(this).remove();
});
});
$("#my_input").autocomplete({
source: function(req, resp) {
$.getJSON("http://localhost/grootjeframework/testproject/json/find/partij/naam/" + encodeURIComponent(req.term), resp);
},
select: function(event,ui){
//do Stuff
}
});
(编辑器将我的 HTML span 视为 span 元素;)所以我无法发布它。供您引用:它只是一个 ID 为“my_span”的普通跨度)
输入和跨度的替换工作正常。没有替换脚本的自动完成也可以正常工作。但是,将两者结合起来,autocompletefunction
就失效了。
最佳答案
“my_input”仅在“my_span”点击时创建,因此当您在其上附加“blur”事件处理程序和自动完成插件时,它尚不存在。
尝试做这样的事情:
$(function () {
$('#my_span').live('click', function () {
var input = $('<input />', {'type': 'text', 'id': 'my_input', 'name': 'my_input', 'value': $(this).html()});
input.live('blur', function () {
$(this).parent().append($('<span />' , {'id': 'my_span'}).html($(this).val()));
$(this).remove();
});
input.autocomplete({
source: function(req, resp) {
$.getJSON("http://localhost/grootjeframework/testproject/json/find/partij/naam/" + encodeURIComponent(req.term), resp);
},
select: function(event,ui){
//do Stuff
}
});
$(this).parent().append(input);
$(this).remove();
input.focus();
});
});
通过这种方式,您可以在元素创建后附加事件处理程序和自动完成。
关于javascript - 将 SPAN 替换为 INPUT 时,JQuery 自动完成功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13218618/