gpt4 book ai didi

javascript - jQuery 自动完成动态新行

转载 作者:行者123 更新时间:2023-11-30 10:33:37 24 4
gpt4 key购买 nike

问题:(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;
});
});

所以上面的代码工作正常。为你的帮助干杯;)

最佳答案

对于您最新的代码,您犯了两个错误:

  1. 在将自动完成应用于文本字段之前增加计数器 i
  2. 通过return false停止了脚本

此外,建议使用 .on() 替换 .live(),因为它在 1.7 版本中已弃用。

演示:http://jsfiddle.net/indream/f8mt4/

$('#addScnt').on('click', function () {
$(...).appendTo(scntDiv);
//i++; Should not be done here
//return false; Stopped the script

//Added the 5 lines below

$(function ($) {
$('#p_scnt_' + i).autocomplete({
source: window.availableTags,
minLength: 1
});
});
i++; // should increase counter here
return false;

});

附注我已将 availableTags 更改为全局变量以使演示正常运行,
但我认为您会使用查询来检索标签。

关于javascript - jQuery 自动完成动态新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15322411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com