简体   繁体   中英

Click event only firing on the first element?

I'm working for my Wordpress project and I created some jQuery code, but it only seems to work on the first element.

Here is my CSS:

<style type="text/css">
    #hide {
        display:none;
    }
</style>

Here is my jQuery:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#show").click(function(){
            $("#hide").toggle();
            return false;
        });
    });
</script>

What am I doing wrong?

You probably have multiple ID's with the same name ( #show and #hide ) - change all those elements to use a class instead ( ID's are supposed to be unique ), and then you could change your code to something like the following:

$(document).ready(function(){
    $(".show").click(function(){
        $(this).toggleClass('hide');
        return false;
    });
});

and slightly change your CSS as well:

.hide {
  display:none;
}

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