w3schoon Posted February 17, 2013 Share Posted February 17, 2013 (edited) Nice be with you everyone! After I've learned setting JQuery selectors in a variables for optimisation.Example: $(document).ready(function(){ $("form").submit(function(){ var a=$("#position"); var b=$("#job"); var c=$("input#religion"); var d="Others"; if (a.val() == "" && b.val() == d ){ b.val("").focus(); return false; } if (c.val() == d){ c.val("").focus(); return false; } }); }); My related question is: Can I set JQuery methods in a variables for optimisation?Example: $(document).ready(function(){ var a=attr("maxlength", 32); $("#specialty").a; }); Thank you. Edited February 17, 2013 by w3schoon Link to comment Share on other sites More sharing options...
callumacrae Posted February 17, 2013 Share Posted February 17, 2013 It'll make your code unreadable and no more efficient. Link to comment Share on other sites More sharing options...
justsomeguy Posted February 18, 2013 Share Posted February 18, 2013 It should also be noted that putting a reference to something in a variable doesn't automatically make it more efficient. In your original code you only use the variable a once, so there's no reason to save that in a variable. It's not more efficient, in fact it now uses memory to save that object in a variable reference when you only needed to refer to it once. You use b and c each potentially twice, so saving that reference in a variable might make it more efficient because it doesn't need to look up the element in the DOM more than once. You're still using the val method more than once though, so it would be better to save the value instead of the element if you only need to refer to the value, the value will use less memory. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now