简体   繁体   中英

How do I get a jQuery function to work with specific elements when they have the same class names?

I have sections (divs) with text in it, but when the text is too long I made it so the text "fades" (with css) and displays a "show more" button, which shows the full text for that specific div when clicked. The problem is that it only works for the first div, and I believe it's because they all have the same class and id name. What's the best way to get around that? Here's my code:

HTML:

<div id="fade-container">
  <div id="fade-content">
   <p>
    Long text goes here...
    <div class="fade-anchor"><span class="btn-primary round-xl small btn-shadow">Show more</span></div>
   </p>
  </div>
</div>

Script:

<script>
$('.fade-anchor').click(function(e){
    e.preventDefault();
    $('#fade-content').css('max-height','none');
    $('.fade-anchor').remove();
});
</script>

By the way, info is being fetched from the database in a php while loop.

When the user clicks on .fade-anchor you can use this to get the element currently selected, you should also use classes instead of ids for multiple elements, like so:

$('.fade-anchor').click(function(e){
    e.preventDefault();
    $(this).parent('.fade-content').css('max-height','none');
    $(this).hide(); // Maybe you should hide instead of removing, in case you want to add a toggle effect later on.
});

You can also check out this jsFiddle with the working version.

Hope it helps.

You can achieve it by e.currentTarget

$('.fade-anchor').click(function(e){
e.preventDefault();
$(e.currentTarget).css('max-height','none');
$('.fade-anchor').remove();});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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