有什么方法可以在使用 json 的数据创建的 "div" 中 select 特定 "tr" 吗?
Is there any way to select specific "tr" in a "div" created with data from json?
我只用 Json 在 div 中创建了一个 table。
div 看起来像这样:
<div id="datatable" class="datatable" data-mdb-hover="true"
data-mdb-border-color="dark"
data-mdb-full-pagination="true"
data-mdb-clickable-rows="true"
>
</div>
然后我创建 table:
const columns = [
{label: 'ID', field: 'id'},
{label: 'Role', field: 'role'},
];
const asyncTable = new mdb.Datatable(
document.getElementById('datatable'),
{columns,},
{loading: true}
)
fetch('/api/roles')
.then((response) => response.json())
.then((data) => {
asyncTable.update(
{
rows: data.map((roles) => ({
...roles,
name: `${roles.id}`,
role: `${roles.name}`,
})),
},
{loading: false}
);
});
现在,如果我像这样单击 tr,我会尝试将 class 更改为“活动”:
// function to select the row
const table = document.getElementById('datatable');
table.addEventListener('rowClick.mdb.datatable', (e) => {
const selected_item_id = e.row.id
//console.log(e);
//event.target._setClassNames("active");
event.target.querySelector("tbody tr").className += "active"
activeT.push(selected_item_id)
});
它正在工作,但只在第一个 tr 中。如果我点击第二个 tr,它会再次将“活动”添加到第一个 tr..
在浏览器控制台中点击 2 次后是这样的。就像你可以在这里看到双重活动一样:
<tr scope="row" data-mdb-index="0" class="activeactive"><td style="" class="" data-mdb-field="id" false="">18</td><td style="" class="" data-mdb-field="role" false="">Admin</td></tr>
也许有人能帮助我!
试试这个
<script>
$('tr').onclick(function (e) {
$(this).toggleClass('active');
})
</script>
我只用 Json 在 div 中创建了一个 table。
div 看起来像这样:
<div id="datatable" class="datatable" data-mdb-hover="true"
data-mdb-border-color="dark"
data-mdb-full-pagination="true"
data-mdb-clickable-rows="true"
>
</div>
然后我创建 table:
const columns = [
{label: 'ID', field: 'id'},
{label: 'Role', field: 'role'},
];
const asyncTable = new mdb.Datatable(
document.getElementById('datatable'),
{columns,},
{loading: true}
)
fetch('/api/roles')
.then((response) => response.json())
.then((data) => {
asyncTable.update(
{
rows: data.map((roles) => ({
...roles,
name: `${roles.id}`,
role: `${roles.name}`,
})),
},
{loading: false}
);
});
现在,如果我像这样单击 tr,我会尝试将 class 更改为“活动”:
// function to select the row
const table = document.getElementById('datatable');
table.addEventListener('rowClick.mdb.datatable', (e) => {
const selected_item_id = e.row.id
//console.log(e);
//event.target._setClassNames("active");
event.target.querySelector("tbody tr").className += "active"
activeT.push(selected_item_id)
});
它正在工作,但只在第一个 tr 中。如果我点击第二个 tr,它会再次将“活动”添加到第一个 tr..
在浏览器控制台中点击 2 次后是这样的。就像你可以在这里看到双重活动一样:
<tr scope="row" data-mdb-index="0" class="activeactive"><td style="" class="" data-mdb-field="id" false="">18</td><td style="" class="" data-mdb-field="role" false="">Admin</td></tr>
也许有人能帮助我!
试试这个
<script>
$('tr').onclick(function (e) {
$(this).toggleClass('active');
})
</script>