简体   繁体   中英

Using same click function for multiple elements (Jquery)

Hi Im having troubles with getting the following to work. Only the first element works, how should I think?

<div class="hi">
    <a id="tabBtn" href="javascript:void(0)"></a>
</div>
<div class="hi">
    <a id="tabBtn" href="javascript:void(0)"></a>
</div>
<div class="hi">
    <a id="tabBtn" href="javascript:void(0)"></a>
</div>

<script>
    $('#tabBtn').on("click",function(){
        if ($(this).parent('.hi').css('max-height') == '65px'){
            $(this).parent(".hi").addClass('open');
        }
        else{
            $(this).parent(".hi").removeClass('open');
        }
    })
</script>

Using the same id on multiple elements is invalid, use a class instead:

  $('.tabBtn').on("click", function() { if ($(this).parent('.job').css('max-height') == '65px') { $(this).parent(".job").addClass('open'); } else { $(this).parent(".job").removeClass('open'); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div class="hi"> <a class="tabBtn" href="javascript:void(0)">Hello</a> </div> <div class="hi"> <a class="tabBtn" href="javascript:void(0)">Hello2</a> </div> <div class="hi"> <a class="tabBtn" href="javascript:void(0)">Hello3</a> </div> 

first thing first id attribute should be ONCE per page

having say that all you need to do is work on the on function from the document and in a selecter way like so

$(document).on("click",".tabBtn",function(){
  //do work
})

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