Javascript onclick requiring two clicks

对着背影说爱祢 提交于 2019-12-12 01:36:16

问题


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



来源:https://stackoverflow.com/questions/23299145/javascript-onclick-requiring-two-clicks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!