文件auto.html有一个由6行组成的表。当用户在文本框中输入值并单击“添加”按钮时,表中的行数会增加。我正在使用所有文本框的class属性来执行基于类选择器的自动完成。现在我需要为动态创建的文本框实现自动完成,我甚至尝试了id选择器(给出内部注释)。我看到了几个与动态添加文本框中的自动完成问题相关的问题,但没有一个能够充分解决我的问题。我在下面提供了我的代码。
auto.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script src="auto.js">
</script>
<script>
var no_of_rows = 6;
var upto = no_of_rows + 1 ;
var total_rows = total_rows ;
$(document).ready(function(){
$('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
$("#but").click(function(){
var no_of_extra = parseInt($("#no_of_extra").val() , 10);
total_rows = no_of_rows + no_of_extra;
$("#mytable").find("tr:gt("+upto+")").remove();
for ( var i = no_of_rows + 1 ; i <= total_rows ; i ++)
{
var tag = "<tr> <td>" + i + "</td> <td> <input class = \"tags\" id = \"T"+i+"\"> </td>";
$("#mytable").append(tag);
/*
$( "#T" + i ).autocomplete({
source: availableTags
});
*/
}
});
});
</script>
</head>
<body >
<input type="text" id="no_of_extra" class="numbersOnly" >
<input type="button" id = "but" value="Add" >
<br><br><br><br>
<table id="mytable">
<tr><th>no</th><th>type</th><tr>
<tr><td>1</td><td><input class ="tags" id = "T1"></td></tr>
<tr><td>2</td><td><input class ="tags" id = "T2"></td></tr>
<tr><td>3</td><td><input class ="tags" id = "T3"></td></tr>
<tr><td>4</td><td><input class ="tags" id = "T4"></td></tr>
<tr><td>5</td><td><input class ="tags" id = "T5"></td></tr>
<tr><td>6</td><td><input class ="tags" id = "T6"></td></tr>
</table>
</body>
</html>
auto.js
$(function() {
var availableTags = [
"Australia",
"Belgium",
"Canada",
"Denmark",
"Ethiopia",
"France"
];
$( ".tags" ).autocomplete({
source: availableTags
});
});
答案 0 :(得分:2)
在auto.js文件外包含availableTags数组,如下所示:
<script>
var availableTags = [
"Australia",
"Belgium",
"Canada",
"Denmark",
"Ethiopia",
"France"
];
var no_of_rows = 6;
var upto = no_of_rows + 1 ;
var total_rows = total_rows ;
$(document).ready(function(){
$( ".tags" ).autocomplete({
source: availableTags
});
$('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
$("#but").click(function(){
var no_of_extra = parseInt($("#no_of_extra").val() , 10);
total_rows = no_of_rows + no_of_extra;
$("#mytable").find("tr:gt("+upto+")").remove();
for ( var i = no_of_rows + 1 ; i <= total_rows ; i ++)
{
var tag = "<tr> <td>" + i + "</td> <td> <input class = \"tags\" id = \"T"+i+"\"> </td>";
$("#mytable").append(tag);
$( "#T" + i ).autocomplete({
source: availableTags
});
}
});
});
</script>
请在此处找到工作演示:Demo