array = on,8816.32,9032.32,8990.167,9038.167,8819.389,9035.389,9059.525,8813.568,9056.726
上面是一个字符串。下面是将值传递给函数trimList 的onclick。
<input type="checkbox" value="9032.32" id="sendpids" onclick="trimList(9032.32)">
使用此处显示的函数https://stackoverflow.com/a/4272526/1794918。我这样做了。
function trimList(cutThis) {
function remove(array,to_remove)
{
const elements = array.split(",");
const remove_index = elements.indexOf(to_remove);
console.log(remove_index);
elements.slice(1, remove_index);
const result = elements.join(",");
return result;
}
let array = checkedList.ids;
let newList = remove(array, cutThis);
checkedList.ids = newList;
console.log(checkedList.ids);
}
在控制台日志中,remove_index 始终为 -1,这意味着它没有在数组中找到变量 cutThis。当它重新加入列表时。它从列表中删除最后一个项目,而不是提交的项目。
如果我删除元素 = array.split(","); 并且只留下元素 = 数组;我可以在控制台日志中看到数字 3。
似乎无法将正确的组合组合在一起以达到预期的结果。
在页面上,有一个复选框列表。我有系统从这些复选框创建值列表。那就是上面的数组。现在,我试图在取消选中该框时从列表中删除该项目。在这种情况下,9032.32未选中,需要搜索该字符串并将该值从列表中删除,然后创建一个新字符串并将其设置为 checkedList.ids 的全局值。
假设checkedList.ids
是您所说的格式的字符串,您有两个问题
首先,elements.slice(1, remove_index);
返回一个新的数组,不修改elements
数组 - 可能意味着elements.splice(1, remove_index);
第二,onclick="trimList(9032.32)"
用一个数字调用trimList
你想要 onclick="trimList('9032.32')" 所以 indexOf 将匹配字符串
把这一切放在一起
<input type="checkbox" value="9032.32" id="sendpids" onclick="trimList('9032.32')">
和
function trimList(cutThis) {
function remove(array,to_remove)
{
const elements = array.split(",");
const remove_index = elements.indexOf(to_remove);
console.log(remove_index);
elements.splice(1, remove_index);
const result = elements.join(",");
return result;
}
let array = checkedList.ids;
let newList = remove(array, cutThis);
checkedList.ids = newList;
console.log(checkedList.ids);
}
但是,您在输入标签中重复了自己9032.32
......那里有一个错字,事情不会像他们应该的那样工作
我会建议
<input type="checkbox" value="9032.32" id="sendpids" onclick="trimList(this.value)">
但是,即使这样也不是最好的解决方案。我实际上建议根本不使用onclick
属性,而是使用element.addEventListener('click', fn)
- 但很难建议确切的代码,因为我不知道你的 HTML 的其余部分,但它可能是这样的:
<input type="checkbox" value="9032.32" id="sendpids">
和
document.getElementById('sendpids').addEventListener('click', trimList);
function trimList() {
const cutThis = this.value;
function remove(array,to_remove)
{
const elements = array.split(",");
const remove_index = elements.indexOf(to_remove);
console.log(remove_index);
elements.splice(1, remove_index);
const result = elements.join(",");
return result;
}
let array = checkedList.ids;
let newList = remove(array, cutThis);
checkedList.ids = newList;
console.log(checkedList.ids);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句