简体   繁体   English

如何使用 Jquery 从列表组行中获取特定项目值

[英]How to get a specific item value from list group row with Jquery

I have a list group with many rows each row has more than two data each item has an id , I wish if i click a such row i can get a custom value, but the way I am using gives me all row's values.我有一个包含多行的列表组,每行有两个以上的数据,每个项目都有一个id ,我希望如果我点击这样的行,我可以获得一个自定义值,但是我使用的方式给了我所有行的值。 If try to change this to items id it does effect only on first row (position 0 of listGrou).如果尝试改变thisid它仅在第一行(listGrou的位置0)的效果。 please help me,请帮我, 列表的样子 , , 单击第二行后的浏览器控制台结果

Html and php code : Html 和 php 代码:

<div  id="listid">  
    <ul class="list-group p-5 col-sm-8 offset-2" id="content">
<?php 
    while ($registered = mysql_fetch_array($query_student)) {
?>
        <li class="list-group-item  list-group-item-action Divlistid" >
            <a href="#">
                <span id="name">
                    <h4><b>
                    <?php echo $registered['firstname']; ?>
                    </b></h4>
                </span>
                <span id="gender">
                <?php echo $registered['gender']; ?>
                </span>
        </li>

<?php 
    } 
?>
    </ul>  
</div> 

Jquery code which is not getting a custom item but all row's items:未获取自定义项而是所有行的项的 Jquery 代码:

$(".list-group-item").click(function(){
    var id = $(this).attr('id')
    var text = $(this).text();
    console.log(id)
    console.log(text)
})

Target your li's by index:按索引定位你的li's

$(".list-group-item").('click',function(){

     var liIndex = $(this).index();
     if( liIndex === 0 ){ // i'm the first li from .list-group }

     // target last - logical
     if( liIndex === $(this).parent().children('.list-group-item').length -1 ){ // i'm the last li from .list-group }

    // target last - hardcoded
     if( liIndex === $('.list-group .list-group-item').length -1 ){ // i'm the last li from .list-group }

})

You can not have multiple elements in your DOM with the same ids.您的 DOM 中不能有多个具有相同 ID 的元素。 You can try to concatenate these ids with the loop counter for example and target elements with jquery using 'class' attribute.例如,您可以尝试将这些 id 与循环计数器连接起来,并使用 'class' 属性使用 jquery 来定位元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM