jQuery Scenario

  • 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};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容