問題:(jQuery)自動完成僅適用於第一個輸入(默認顯示)。它不適用於使用添加行函數添加的其他行。動態新行上的jQuery自動完成
我已閱讀其他帖子,並瞭解我必須使用類而不是id。但它仍然不起作用。
我正在使用jQuery自動完成和一些JavaScript來添加和刪除特定ID的行。
這裏是標頭:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
這裏是jQuery代碼:
jQuery(document).ready(function ($) {
/* availableTags = [
"Demo",
"Senna",
"Adam",
"Eva",
];*/
$('.autofill').autocomplete({
source:'suggest.php', minLength:2
});
});
下面是HTML代碼:
<div class="content-left">
<a href="#" id="addScnt">Add rows</a>
<div id="p_scents">
<p>
<label style="margin-bottom:10px;" for="p_scnts">
<input class="autofill" type="text" id="p_scnt" size="20" name="p_scnt[]"
value="" placeholder="Enter text" />
</label>
</p>
</div>
</div>
**Here is the Javascript to add rows:**
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').on('click', function() {
$('<p><label style="margin-bottom:10px;" for="p_scnts"><input class="autofill" type="text" name="p_scnt[]" size="20" id="p_scnt_' + i + '" value="" placeholder="Add text" /></label for="remScnt"> <label style="padding-left:400px;"><a href="#" id="remScnt">Remove</a></label></p>').appendTo(scntDiv);
//i++;
//return false;
//Added the 5 lines below
$(function ($) {
$('#p_scnt_' + i).autocomplete({
source:'suggest.php', minLength:2
});
});
i++;
return false;
});
$('#remScnt').on('click', function() {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
所以上面的代碼工作正常。歡呼所有的幫助;)
嘗試使用.on()而不是.live()。 .live()函數從jQuery 1.7開始已棄用。你也應該爲此發佈一個js小提琴,人們將能夠更輕鬆地爲你提供幫助。 – user1048676 2013-03-10 12:53:12
我試過.on()而不是.live(),但我仍然有同樣的問題,即自動完成只適用於第一行。我沒有使用js小提琴,但會嘗試設置一個。 – Adam 2013-03-10 13:00:15