美文网首页
jQuery Scenario

jQuery Scenario

作者: westmoor | 来源:发表于2015-06-04 15:01 被阅读0次
    • Check if a checkbox is checked. often used on agreement dialog
      demo(checkbox)

    • Check if elements are visible
      $category.is(":visible")

    • Even if jQuery select element that doesn't exist, it would not report error.
      so when check if an element exists
      cannot use this method

    if ($("#id")){
        // do stuff
    }
    

    Should check its length

    if($("#id").length > 0){
        // do stuff
    }
    
    • toggle functions
    $toggleBtn.toggle(function(){
        // show element
        }, function(){
        // hide element
    })
    

    hover functions

    $("#foo").hover(function(){
     // do stuff
    }, function(){
        // do stuff
    });
    
    • Difference between window.onload and $(document).ready()
      The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content(eg. images) also has been loaded

    • Why use .bind() over .click() or any other event?
      They're effectively the same, using bind() allows you to make use of namedspaced events This is especially useful when writing plugins.
      and also yo ucan use multiple events

    $("#foo").bind('mouseenter mouseleave', function(){
        $(this).toggleClass('entered');
    });
    
    • event bubbling and event.stopPropagation()
      The concept of 'bubbling up ' is like if you have a child element with a click event and you don't want it to trigger the click event of the parent. You can use event.stopPropagation()
    $("#foo").bind('click', function(event) {
        // do stuff
        event.stopPropagation();
    });
    

    similar is preventDefault() method. You first create event in function and use it to call methods.

    • event capturing

    Animation

    • Check if element is in animation
      if($("#foo").is(":animated"))
    • stop() is useful when dealing with starting animation when previous one is not finished.
      (otherwise, the new animation will wait for previous one to finish in queue).
    $("#foo").hover(function(){
        $(this).stop()
                    .animate({height:"150", width: "300"}, 200);
    }, function() {
        $(this).stop()
                    .animte({height:"22", width:"60"}, 300};
    

    if animation is a combo

    $("#foo").hover(function(){
        $(this).stop(true)  // means clear the queue
                    .animate({height:"150", width: "300"}, 200);
                    .animate({blabla}, 300);
    }, function() {
        $(this).stop()
                    .animte({height:"22", width:"60"}, 300};
    

    相关文章

      网友评论

          本文标题:jQuery Scenario

          本文链接:https://www.haomeiwen.com/subject/cwpdqttx.html