使用JavaScript和MySQL时,表格首条记录后无法显示目标值
问题分析与解决方案
问题根源
所有模态框内的下拉选框都使用了相同的id="product_info",价格输入框也都用了id="price"。由于document.getElementById()只会返回页面中第一个匹配该ID的元素,因此只有第一条记录的模态框能正常触发价格显示,后续记录的模态框无法生效。
修复方案
- 为每个模态框内的下拉选框和价格输入框设置唯一ID,结合用户表的
id字段区分(比如product_info_用户ID、price_用户ID)。 - 使用事件委托绑定change事件,避免重复绑定,同时确保所有下拉选框的变化都能触发价格更新。
修改后的代码
表格部分
<table> <tr> <th>Name</th> <th>Surname</th> <th>Phone Number</th> <th>Gender</th> </tr> <?php $sql = "SELECT * FROM test_table"; $result = $db->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { ?> <tr> <td><?php echo $row["name"]; ?></td> <td><?php echo $row["surname"]; ?></td> <td><?php echo $row["phone_number"]; ?></td> <td><?php echo $row["gender"]; ?></td> <td> <ul class="t-dropdown-list"> <a data-toggle="modal" data-target="#SetProductCustomer<?= $row["id"]; ?>"> <li class="t-dropdown-item">Edit</li> </a> </ul> </td> </tr> <div class="modal fade" id="SetProductCustomer<?= $row["id"]; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-content"> <a href="test.php"><span class="close">×</span></a> <p><?php echo $row['name']; ?> </p> <!-- 为select设置唯一ID,并添加统一类名 --> <select style="width: 100%;" name="" id="product_info_<?= $row["id"]; ?>" class="browser-default custom-select-new product-select"> <?php $records = mysqli_query($db, "SELECT * FROM products"); while ($data = mysqli_fetch_array($records)) { echo '<option value="' . $data['product_name'] . '" data-price="' . $data['price'] . '">' . $data['product_name'] . '</option>'; } ?> </select> <!-- 为价格输入框设置唯一ID --> <input type="text" name="price" id="price_<?= $row["id"]; ?>" class="price-input"/> </div> </div> <?php } } ?> </table>
JavaScript部分
<script> // 事件委托:监听所有.product-select的change事件 document.addEventListener('change', function(e) { if (e.target.classList.contains('product-select')) { // 获取当前选中项的价格 const selectedPrice = e.target.options[e.target.selectedIndex].getAttribute('data-price'); // 从select的ID中拆分出用户ID,定位对应的价格输入框 const userId = e.target.id.split('_')[1]; document.getElementById(`price_${userId}`).value = selectedPrice; } }); </script>
方案说明
- 唯一ID:确保每个下拉选框和输入框都能被独立识别,避免ID冲突。
- 事件委托:仅绑定一次事件,即可处理所有下拉选框的变化,性能更优,且支持动态新增的模态框。
- 关联匹配:通过select的ID拆分出用户ID,精准找到对应的价格输入框,保证价格显示到正确的位置。
内容的提问来源于stack exchange,提问作者Gareth159753
相关产品推荐
相关产品推荐

