Javascript onclick requiring two clicks

2019-09-18 03:08发布

问题:

I have this box that transforms in a bigger box when clicked (getting class). But it is taking 2 clicks, and not only one as it was suposed to take.

.clientes {width:170px;height:27px;background-image:url('../imagens/clients.gif');-webkit-transition:1s;}
.clientes-clicked {width:356px !important;height:154px !important;background-image:url('../imagens/clients-big.png') !important;-webkit-transition:1s;}

<script>    
    var clientesclick = function(){
    $('.clientes').on('click', function(e) {
      $('.clientes').toggleClass("clientes-clicked"); //you can list several class names 
      e.preventDefault();
    });
    }
</script>

回答1:

You're making this more complicated than it needs to be. You could simply do:

$('.clientes').click(function(){
    $(this).toggleClass('clientes-clicked');
});

A fiddle: http://jsfiddle.net/64XQ3/

And, as was pointed out above, your jQuery should be wrapped in

$(document).ready(function(){
    // code here
});


回答2:

Try it like this

<script>   
    $(document).ready(function() {
        $('.clientes').on('click', function(e) {
          $('.clientes').toggleClass("clientes-clicked"); //you can list several class names 
          e.preventDefault();
        });
    });
</script>

Not too sure why you are assigning it to a variable but it would not run right away, instead it will be executed when you call that method (I guess this is first click) and then afterwards your dom elements will have the event (second click).

Using $(document).ready it will run once all the dom is ready, then when you first click on your elements they should already have the event