用php生成列表
我使用PHP生成了一个列表,其中包含从数据库中选择的元素。它工作得非常好。但问题是,当我尝试使用jquery获取用php生成列表,php,jquery,html,mysql,Php,Jquery,Html,Mysql,我使用PHP生成了一个列表,其中包含从数据库中选择的元素。它工作得非常好。但问题是,当我尝试使用jquery获取li索引时,它只会给我提供奇数索引。就像我单击第一个元素时,它会给出以下索引: 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 sh
li
索引时,它只会给我提供奇数索引。就像我单击第一个元素时,它会给出以下索引:
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);
})
-
JS:
$('ul li')。单击(函数(){
var index=$(this.index();
控制台日志(索引);
})
您在html中放置了(开始标记)而不是(结束标记)。请更正它,它将解决您的问题,并为您提供正确的索引
<ul style="list-style:none;">
<?php while($row = $result->fetch_assoc()):?>
<li class="list-group-item"><?=$row['name']?></li>
<?php endwhile ?>
</ul>
这只是一个让它工作的技巧,你应该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);
})
-
$('ul li')。单击(函数(){
var index=$(this.data('index');
控制台日志(索引);
})
请发布一些相关的代码/html来理解问题。还可以通过更正indexeshappy来帮助您指定具体的目标:)。如果你觉得答案有用,你可以接受并投票表决