php, jquery only first id working normal

隐身守侯 提交于 2021-02-05 08:08:08

问题


I have the following code in .php (code is edited for easier understanding).

while($row = mysql_fetch_array($biznis)){
<div id='listItem'>
    <div id='listPic'>
        <img src='../../social/images/avatar/empty_avatar_full.jpg'></img>
    </div>
    <div id='listCont'>
        <span>abcde<i>(request pending)</i></span>                              
    </div>
    <div id="listInfo">
        <span id='info'>More info</span>
    </div>
    <div style='clear:both;'></div>

    <div id='moreInfo'>
        <span>Invitation sent: xx-yy-zzzz</span>
    </div>
</div>

<div style='clear:both;'></div>
}

So the code is nothing special, I just get all records from the table lined up. So now, here is the problem, as you can see, I use the same ids for the same elements.

Jquery code

$(document).ready(function () {
    $("#moreInfo").hide();

    $("#info").click(function(){
    $("#moreInfo").slideToggle();
});
});

OK so here are now the problems. Only first div (#moreinfo) is hidden, all the others are shown. And only first span (#info) is toggling the slider.

I tried with putting the counter for ids, and jquery each function, but nothing realy worked as i imagined.

Ty, Sebastian


回答1:


Element IDs should be unique identifiers for that element. Use classnames for generic selectors:

<? while($row = mysql_fetch_array($biznis)): ?>
<div class="listItem">
    <div class="listPic">
        <img src="../../social/images/avatar/empty_avatar_full.jpg"></img>
    </div>
    <div class="listCont">
        <span>abcde<i>(request pending)</i></span>                              
    </div>
    <div class="listInfo">
        <span class="info">More info</span>
    </div>
    <div style="clear:both;"></div>
    <div class="moreInfo">
        <span>Invitation sent: xx-yy-zzzz</span>
    </div>
</div>
<div style="clear:both;"></div>
<? endwhile; ?>

And change your jQuery to:

$(function() {
   $('.moreInfo').hide();
   $('.info').click(function() {
      $('.moreInfo').slideToggle();
   });
});

Edit

$('.info').click(function() {
   $(this).parent().siblings('.moreInfo').slideToggle();
});



回答2:


use class and not ids because you're in a while loop. An id exists only once.

And update your JS.



来源:https://stackoverflow.com/questions/14922717/php-jquery-only-first-id-working-normal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!