简体   繁体   English

对多个元素使用相同的单击功能(jQuery)

[英]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: 对多个元素使用相同的id无效,请改用class

  $('.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 第一件事,第一id属性应该是ONCE每页

having say that all you need to do is work on the on function from the document and in a selecter way like so 只需说一下,您需要做的就是通过documenton功能并以类似选择器的方式进行操作

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

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

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