【问题标题】:Generated list with php用php生成的列表
【发布时间】:2018-08-02 09:43:39
【问题描述】:

我使用 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 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);
})

【问题讨论】:

  • 请发布一些相关的代码/html来理解问题。还可以通过更正索引来明确您的目标

标签: php jquery html mysql


【解决方案1】:

您在 html 中放置了 &lt;li&gt;(开始标签)而不是 &lt;/li&gt;(结束标签)。请更正它,它将解决您的问题并为您提供正确的索引

<ul style="list-style:none;">
        <?php while($row = $result->fetch_assoc()):?>

            <li class="list-group-item"><?=$row['name']?></li>

        <?php endwhile ?>
    </ul>

【讨论】:

  • 很高兴为您提供帮助:)。如果觉得有帮助,您可以接受并投票赞成这个答案
【解决方案2】:

它只是一个 hack 让它工作你应该 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);
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多