开发者

Jquery onclick event requires two clicks

On click, I want to hide/show some html code(which is obtained via a GET request to another page). It works but the problem is that it requires two clicks instead of one.

There is one other question that seems related but I am not able to understand that.

  <script>
     $(document).ready(function(){
        $(".quote-toggle").click( function(event) {
            var id = $(this).attr('id');
            $.get( $(this).attr('href'), function(msg) {
                if($("#toggler_" + id).html()=='show') {
                    $("#" + id).html(msg);
                    $("#toggler_" + id).html('hide'); 
                  }
                else {
                    $("#" + id).html('');
                    $("#toggler_" + id).html('开发者_C百科show'); 
                 }
            });
            event.preventDefault();
        });
     });
   </script>

This is my first time with jquery/javascript. Any explanation or suggestions for the code would be much appreciated. [Edit]

jsfiddle: http://jsfiddle.net/KCLf5/1/


If I had to guess, $("#toggler_" + id)'s html is not set to show. So the first click will set it to show and the second will load the data.

Make sure that the toggler has the correct html when the page loads


  1. First of all - you shouldn't do get request on hide element.
  2. Second - event.preventDefault should be at the start of event. It will save you from unexcepted behaviour on javascript errors.

Here is code, that uses these 2 recomendations:

    $(document).ready(function(){
      $(".quote-toggle").click( function(event) {
        event.preventDefault();
        var id = $(this).attr('id');
        var url = $(this).attr('href');
        if($("#" + id).html()=='') {
            $.get(url, function(msg) {
                $("#" + id).html(msg);
                $("#toggler_" + id).html('hide'); 
            });
         } else {
            $("#" + id).html('');
            $("#toggler_" + id).html('show'); 
         }
      });
    });


For two days I wrestled with having the "2-clicks-required-to-load-first-external-html" problem.

After one would load, requiring 2 clicks, the rest would behave and load on 1 click.

I easily solved this by creating a blank html file, and placing its load command on the line following "(document).ready". Nothing else I tried from forums would work for me, but this did on the very first try.

I had noticed that the JS file wanted one html file loaded before it would load any of the others, so I gave it one to load automatically. Simple fix and works like a charm!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜