从对象取数异常:控制台输出正确但页面展示偏移一位求助
问题解决:页面展示信息偏移一位
问题根源
你的代码存在两个核心问题:
- 重复ID导致选择器错误:循环创建多个
<table>时,每个都设置了相同的id="table"、id="personName"、id="personId",HTML中ID必须唯一,这会导致jQuery选择器$("th#personName")每次都选中页面里的第一个对应元素,而非当前循环的table元素。 - 错误的元素插入位置:你创建了
newRow这个<tr>,但没有把用户姓名和ID的<th>放入其中,反而直接插入到表头的<th>后面,导致表格结构混乱,出现展示偏移。
修正后的代码
JavaScript部分
$(document).ready(function() { for (person of personInformation) { const personTable = document.createElement("table"); // 移除重复ID,构建基础表头结构 personTable.innerHTML = "<thead><th>Name</th><th>person ID</th></thead>"; // 用类名标识表格,避免重复ID冲突 personTable.classList.add("person-table"); const newRow = document.createElement("tr"); newRow.classList.add("personRow"); const first_name = document.createElement("td"); const person_id = document.createElement("td"); person_id.textContent = person.person_id; first_name.textContent = person.first_name; // 将用户信息单元格放入当前行,再添加到表格 newRow.appendChild(first_name); newRow.appendChild(person_id); personTable.appendChild(newRow); for (fees of person.fees) { const feeRow = document.createElement("tr"); const fee = document.createElement("td"); const amount = document.createElement("td"); fee.textContent = fees.name; amount.textContent = fees.amount; feeRow.appendChild(fee); feeRow.appendChild(amount); personTable.appendChild(feeRow); } const persons = document.getElementById('test'); persons.appendChild(personTable); } // 修正搜索功能逻辑,针对用户行进行过滤 $('#personSearch').on('input', function() { let value = $(this).val().toLowerCase(); $('.personRow').each(function() { const rowText = $(this).text().toLowerCase(); // 根据输入显示/隐藏对应用户的表格 $(this).closest('.person-table').toggle(rowText.indexOf(value) > -1); }); }); });
HTML部分(补充缺失的搜索框)
<body> <div class="container"> <div class="col-md-12"> <div class="panel panel-default"> <!-- 补充搜索框,对应JS中的#personSearch选择器 --> <input type="text" id="personSearch" placeholder="搜索用户"> <div id="test"></div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script> <script> const personInformation = [{ "person_id": 1, "first_name": "James", "fees": [{ "name": "first location", "amount": "$35" }, { "name": "fee", "amount": "amount calculated" }, { "name": "fee3", "amount": "a million in spacecash" } ] }, { "person_id": 2, "first_name": "Jordan", "fees": [{ "name": "second location", "amount": "$40" }, { "name": "fee", "amount": "amount calculated" } ] } ]; </script> </body>
修正说明
- 移除所有重复ID,改用类名标识元素,避免选择器混淆。
- 将用户姓名和ID的单元格正确放入对应的行内,表格结构符合HTML规范。
- 修正搜索功能逻辑,现在可以根据输入正确过滤用户表格。
内容的提问来源于stack exchange,提问作者homsAU
相关产品推荐
相关产品推荐

