我基本上有2个活动。最上面一个从jQuery自动完成中选择选择并将其输出到div searchresultdata 。第二个从#* search_input *获取内容并将其输出到 searchresultdata
var devices = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$("#search_input").autocomplete({
source: devices,
select: function(e, i) {
var search_input = i.item.value;
document.getElementById('searchresultdata').innerHTML = search_input;
}
});
//Append div with contents from function sendSelected
$("#search_input").on("keyup change", function() {
var search_input = $(this).val();
if (search_input.length > 1 || search_input == '*') {
document.getElementById('searchresultdata').innerHTML = "Everything";
}
document.getElementById('searchresultdata').innerHTML = search_input;
});
有关实例,请参阅: http://jsfiddle.net/k2SMb/4/
无论如何,我可以把它合二为一,使它更整洁一点吗?
答案 0 :(得分:1)
你可以通过将两个事件链接在一起来使它更整洁,然后你可以使用jQuery的$('#id_selector'),最后当你只需要它一次时,不用费心去写变量。结果:
$("#search_input").autocomplete({
source: devices,
select: function(e, i) {
$('#searchresultdata').text(i.item.value);
}
}).on("keyup change", function() {
var search_input = $(this).val();
if (search_input.length > 1 || search_input == '*') {
$('#searchresultdata').text("Everything")
}
$('#searchresultdata').text(search_input);
});