从数据列表中移除一个项目 [英] Remove an item from datalist
问题描述
我有一个工作的Ajax调用和填充数据的函数。数据列表用于从有限列表中选择在页面上添加到UL元素。一旦我从数据列表中添加一个到实际列表,我想从数据列表中删除该选项。我使用的蛮力方法是清除数据列表并重新填充数据。
函数populate_datalist_from_array(list_id,list_str)
{
clearChildren(list_id);
var arr = eval(list_str);
for(var i = 0; i< arr.length; i ++){
var opt = document.createElement('option');
opt.innerHTML = arr [i];
opt.value = arr [i];
document.getElementById(list_id).appendChild(opt);
}
}
函数clearChildren(parent_id){
var childArray = document.getElementById(parent_id).children;
if(childArray.length> 0){
document.getElementById(parent_id).removeChild(childArray [0]);
clearChildren(parent_id);
}
}
我已验证 list_str
对象是正确的。即它只包含当前列表中尚未包含的选项。但是在用新列表调用 populate_datalist_from_array
之后,下拉列表中的数据列表不会更改。这是因为浏览器本质上编译了所有的值(比如它是一个基于浏览器的普通自动完成)并且不会忘记我想要移除的值?
<如果 list_str
确实没问题,那么你的代码就可以运行。您可以通过 jsFiddle 进行检查。
您描述的行为的最普遍的原因是您的代码刷新页面。如果您从链接的小提琴中的更改选项按钮中删除 type =button
,则会出现错误(由于小提琴本身)。在你的页面中,你可能有类似的调用 populate_datalist_from_array()
。注意,在一个活动的文本输入上也会出现 Enter 会执行提交/刷新。
I have a working Ajax call and function that populates a datalist. The datalist is used to select from a finite list an addition to an UL element on the page. Once I add one from the datalist to the actual list, I want to remove that option from the datalist. The brute force method I'm using is to clear the datalist and repopulate it.
function populate_datalist_from_array(list_id, list_str)
{
clearChildren( list_id );
var arr = eval ( list_str );
for (var i = 0; i < arr.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = arr[i];
opt.value = arr[i];
document.getElementById(list_id).appendChild(opt);
}
}
function clearChildren( parent_id ) {
var childArray = document.getElementById( parent_id ).children;
if ( childArray.length > 0 ) {
document.getElementById( parent_id ).removeChild( childArray[ 0 ] );
clearChildren( parent_id );
}
}
I've verified that the list_str
object is correct. i.e., it contains only the options not already in the current list. But after calling populate_datalist_from_array
with that new list, the datalist in the dropdown doesn't change. Is this because the browser has essentially compiled all of the values that were there (like it were a normal, browser-based autocomplete) and doesn't 'forget' the values that I want removed?
If list_str
really is OK, your code works. You can check it in action at jsFiddle.
The most general reason for a behaviour you've described, is that your code refreshes the page. If you remove type="button"
from the "Change options" button in the linked fiddle, you'll get an error (due to the fiddle itself). In your page you probably have something similar invoking populate_datalist_from_array()
. Notice, that also hitting Enter on an active text input will do submit/refresh.
这篇关于从数据列表中移除一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!