首页 > 解决方案 > 用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);
})

标签: phpjqueryhtmlmysql

解决方案


让它工作你应该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);
})

推荐阅读