Jump to content

Set JQuery methods in a variables for optimisation


Recommended Posts

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 by w3schoon
Link to comment
Share on other sites

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

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 account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...