开发者

Optimize jQuery code

Greetings,

Just built some stuff with jQuery, everything works perfect(!), but I would like it to be as optimzed as po开发者_StackOverflow社区ssible.. what small changes can I do to my code?

  $(document).ready(function() {

 // hide the indicator, we use it later
 $(".indicator").hide();

 // start the animation of the progressbar 
 $(".fill").animate({ width: "50px",}, 4000, function() { $(".indicator").effect("pulsate", { times:999 }, 2000);});

 // notify-me ajax function
 $(".btn-submit").click(function() {  

  // get the variable email and put it in a new variable
  var email = $("input#mail").val();   
  var dataString = 'mail='+email;

  $.ajax({
   type: "POST",
   url: "/mail.php",
   data: dataString,
   dataType: "json",
   success: function(msg){

    // JSON return, lets do some magic
    if(msg.status == "ok") { 
     $("#response-box").fadeIn("slow").delay(2000).fadeOut("slow");
     $("#fade").fadeIn("slow").delay(2000).fadeOut("slow");
     $("#response-box .inner").html("<h1>Thank you.</h1>We'll keep in touch!");
     $("#mail").val("e.g. name@example.com");
    } else { 
     $("#response-box").fadeIn("slow").delay(2000).fadeOut("slow");
     $("#fade").fadeIn("slow").delay(2000).fadeOut("slow");
     $("#response-box .inner").html("<h1>Oops.</h1>Please try again!");
    }
   }
  });

  //make sure the form doesn't post
  return false;

 });

});


There are two principal things in your code that I would change:

First: dataString = 'mail='+email; This is not the best way to set this request parameter. email could easily contain characters that should be encoded when put into a HTTP request. You could do this by using jQuery.param:

dataString = jQuery.param({mail: email});

This will encode characters that have special meaning in an HTTP request, and should make the code more reliable. Alternatively, and slightly faster, you could use the native JS function encodeURIComponent:

datastring = 'mail=' + encodeURIComponent(email);

Second, you are using return false to avoid the default action occuring. I prefer to use event.preventDefault. This is firstly stylistic -- it makes it more clear what you are intending to achieve; secondly, you can put it at the beginning of your handler function. Therefore, if you have an error in the rest of your function for whatever reason, the default action is still prevented.

There may be some other enhancements that could be achieved in terms of the selectors, but it is impossible to tell without seeing your HTML.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜