我想开发我的简单自动完成插件,我对JQuery自动完成插件不感兴趣。
我只想在输入文本的正下方添加一个潜水,假设这个代码可以工作,我做错了什么?实现这一点的方法是什么?
JSFiddle
如果你不想打开小提琴,这是代码:
$("#txtSearch").keypress(function (e) {
if ($("#txtSearch").val().length >= 2) {
var pos = $("#txtSearch").position();
$('<div />', {
'html': "xxxxxxxxx xx x"
}).css({
top: pos.top,
left: pos.left,
width: '300px',
position: 'absolute',
'background-color': 'Yellow'
}).appendTo($("#txtSearch"));
}
});
试试下面的代码,
$("#txtSearch").keypress(function (e) {
if ($("#txtSearch").val().length >= 2) {
var pos = $("#txtSearch").position();
$('<div />')
.html("xxxxxxxxx xx x")
.css({
top: pos.top + $("#txtSearch").height() + 1,
left: pos.left,
width: '300px',
position: 'absolute',
'background-color': 'Yellow'
}).insertAfter($("#txtSearch"));
}
});
演示:http://jsfiddle.net/uZF5g/1/
不能追加到(.appendTo
)空的内容模型元素。请改用.insertAfter
(或.insertBefore
)。您可能还希望top
至少添加到输入的高度。
http://jsfiddle.net/uZF5g/3/
$("#txtSearch").keypress(function (e)
{
if ($("#txtSearch").val().length >= 2)
{
$('#txtSearch').after('<div id="someID">');
$('#someID').html('xxxxxxx xx x')
.css({
top: pos.top,
left: pos.left,
width: '300px',
position: 'absolute',
'background-color': 'Yellow'
})
.appendTo($("#txtSearch"));
}
});