已为我提供了一个使用DOM创建的表,现在我必须使用if语句来打印该表的特定区域。例如,在第二张照片中,当我单击 1-200万时,它应该显示表格,但仅显示人口在1到200万之间的国家。我的老师几乎没有教过我们JavaScript,现在给了我们一个使用JavaScript If语句的DOM作业。如果有人可以在我单击上方的链接/按钮时对如何打印表格的特定部分进行解释,我将不胜感激。谢谢!
答案 0 :(得分:0)
以下是路线图:
for
(或for ... in
)语句遍历子菜单,并使用addEventListener()
在每个菜单上附加一个点击事件监听器this
将引用您单击的<li>
(或<a>
或任何元素)(并链接到事件)。因此,您可以访问DOM单击的元素的数据或属性。<table>
语句,以所需的方式过滤if
。 (甚至更好:switch
语句)视觉上,行将被隐藏。在Javascript中,您将更新元素的style
属性。下面是一个例子。我建议您尝试用我给您的元素自己做。如果您真的迷路了,请打开该代码段。
示例:
我在下面使用的其他功能/方法/语句:
querySelectorAll()
,dataset
,instanceof
,parseInt()
,onload
,children
>
// Always interact with the DOM when it is fully loaded.
window.onload = () => {
// Gets all <button> with a "data-filter-case" attribute.
const buttons = document.querySelectorAll('button[data-filter-case]');
// For each <button>, attach a click event listener.
for (let i in buttons) {
const button = buttons[i];
// The last item of "buttons" is its length (number), so we have to check if
// it is a HTMLElement object.
if (button instanceof HTMLElement) {
button.addEventListener('click', filterTable); // Will execute the "filterTable" function on click.
}
}
}
// The function which will filter the table.
function filterTable(e) {
// Useless in my exemple, but if you have <a> instead of <button>,
// it will not execute its original behavior.
e.preventDefault();
// Get the value of "data-filter-case" attribute.
const filterCase = this.dataset.filterCase;
// Get all table body rows.
const tableRows = document.querySelectorAll('table > tbody > tr');
// Update display style of each row in function of the case.
for (let i in tableRows) {
const row = tableRows[i];
if (row instanceof HTMLElement) {
if (filterCase === 'more-than-44') {
if (parseInt(row.children[1].innerText) <= 44) {
// Hide the row.
row.style.display = 'none';
} else {
// Reset display style value.
row.style.display = '';
}
} else if (filterCase === 'less-than-27') {
if (parseInt(row.children[1].innerText) >= 27) {
row.style.display = 'none';
} else {
row.style.display = '';
}
} else if (filterCase === 'reset') {
row.style.display = '';
}
}
}
}
<button type="button" data-filter-case="more-than-44">More than 44</button>
<button type="button" data-filter-case="less-than-27">Less than 27</button>
<button type="button" data-filter-case="reset">Show all</button>
<table>
<thead>
<tr>
<th>ID</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>45</td>
</tr>
<tr>
<th>2</th>
<td>50</td>
</tr>
<tr>
<th>3</th>
<td>24</td>
</tr>
</tbody>
</table>