javascript - 如何存储到数组
问题描述
我正在使用 React Hooks 和 jQuery 制作一个方法,其工作原理如下:
按下该ctrl
键时,可以从表中选择多行。我只想在单击 ctrl 时将此行的 id 存储在数组中,但是每次单击一行时,数组似乎都会重新启动,而不是存储单击行的所有 id。
此外,由于此 jquery 代码中不存在数组,因此我使用了一个钩子。请问有人可以帮我吗?这是我的代码,在此先感谢。
const Mapa = (props) => {
const [groupOfIntersections, setGroupOfIntersections] = useState('');
const arrayOfInt = [];
$('.ui.small.celled.table tbody tr').on('click', (e) => {
if (e.ctrlKey) {
if($(e.target.parentNode).hasClass("active")) {
$(e.target.parentNode).removeClass("active");
} else {
arrayOfInt.push($(e.target.parentNode).attr('class'));
console.log('arrayOfInt', arrayOfInt);
setGroupOfIntersections(arrayOfInt);
$(e.target.parentNode).addClass("active");
}
} else if (!e.ctrlKey){
$('.ui.small.celled.table tbody tr').removeClass("active");
$(e.target.parentNode).addClass("active");
}
});
console.log('groupOfIntersections', groupOfIntersections);
console.log('arrayOfInt', arrayOfInt);
.
.
.
};
解决方案
这个arrayOfInt
常量有问题,实际上你不需要额外的对象,因为你可以使用现有的groupOfIntersections
对象来执行所有的操作。
const Mapa = (props) => {
const [groupOfIntersections, setGroupOfIntersections] = useState('');
$('.ui.small.celled.table tbody tr').on('click', (e) => {
if (e.ctrlKey) {
if($(e.target.parentNode).hasClass("active")) {
$(e.target.parentNode).removeClass("active");
} else {
let tempGroup = [...groupOfIntersections]
tempGroup.push($(e.target.parentNode).attr('class'));
console.log('tempGroup', tempGroup);
setGroupOfIntersections(tempGroup);
$(e.target.parentNode).addClass("active");
}
} else if (!e.ctrlKey){
$('.ui.small.celled.table tbody tr').removeClass("active");
$(e.target.parentNode).addClass("active");
}
});
console.log('groupOfIntersections', groupOfIntersections);
console.log('arrayOfInt', tempGroup);
.
.
.
};
推荐阅读
- windows - WTSClientInfo 在 Windows 10 操作系统上通过 RDP 连接返回 NULL
- javascript - yeoman 和 rxjs - 无法识别的导入路径
- python-3.x - 无法从树莓派 4 上的 gevent.event 导入事件
- java - 如何在 Java 8 上的两个日期间隔之间获得相互(伴随)天数?
- python - 调试 Django 信号处理程序
- javascript - Javascript对象固定按键排序
- r - 如何使用多个(或重复)文本数据在 r 中透视表?
- r - 有人知道避免点标签在 R 中重叠的功能吗?
- java - 使用命令行界面执行maven项目
- c - 仅当数组中有足够空间时,如何保存 scanf 输入?如何重新分配数组以让 scanf 输入适合?