Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用php生成列表_Php_Jquery_Html_Mysql - Fatal编程技术网

用php生成列表

用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

我使用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);
})
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来帮助您指定具体的目标:)。如果你觉得答案有用,你可以接受并投票表决