php - 用php生成的列表
问题描述
我使用 PHP 生成了一个列表,其中包含从数据库中选择的元素。它工作得很好。但问题是当我尝试li
使用 jquery 获取索引时,它只会给我奇怪的索引。就像当我单击第一个元素时,它会给出这些索引:
home(index 0: it should be 0)
,about(index 2: actually it should be 1)
,about(index 4: actually it should be 2)
,about(index 6: actually it should be 3)
,about(index 8: actually it should be 4)
,about(index 10: actually it should be 5).
我使用了 while 循环来生成这个id
。
<ul style="list-style:none;">
<?php while($row = $result->fetch_assoc()):?>
<li class="list-group-item"><?=$row['name']?><li>
<?php endwhile ?>
</ul>
JS:
$('ul li').click(function() {
var index = $(this).index();
console.log(index);
})
解决方案
让它工作你应该fetchAll
使用并使用for
循环只是一个技巧
<ul style="list-style:none;">
<?php $i = 0; while($row = $result->fetch_assoc()):?>
<li class="list-group-item" data-index="$i" ><?=$row['name']?><li>
<?php $i++ ; endwhile ?>
</ul>
$('ul li').click(function() {
var index = $(this).data('index');
console.log(index);
})
推荐阅读
- javascript - 如何将在动态 HTML 表中输入的项目添加到模型绑定列表
- html - CSS - @media 标签不会覆盖较小的最大宽度
- python - Pandas read_csv 挂起代码没有错误,但只是有时
- javascript - Javascript/JQuery - 在具有特定值的单元格之前和之后更改 HTML 表格单元格的背景颜色
- java - 并行执行 Spring 初始化 Bean
- javascript - React.js:如何在自定义属性上过滤 JSX 元素数组?
- macos - Darwin 10.15 上的自修改代码导致“畸形的 mach-o 图像”?
- javascript - Nodejs中的导入类失败
- javascript - Typescript React handleChange() 或 handleSubmit() 表单不工作
- c++ - 如何删除使用 _strdup() 创建的 const char*