开发者

How to use a reference variable in a jQuery?

开发者 https://www.devze.com 2023-03-16 10:20 出处:网络
I learned that using a reference variable is faster than using $() every line of code (see my previous question): jQuery - Is it okay to use $('#ElementId') everytime?. Now my question is how

I learned that using a reference variable is faster than using $() every line of code (see my previous question): jQuery - Is it okay to use $('#ElementId') everytime?. Now my question is how can I use this reference variable to maximize the power of jQuery? Please see the example below:

Without开发者_高级运维 reference variable:

var ValueOfSelected = $('#SelectElementId option:selected').val();

With reference variable (pseudo-code):

var SelectElement = $('#SelectElementId');
var ValueOfSelected = $(SelectElement).SelectedOption.val();

Note that SelectedOption.val() is the pseudo-code here. Is there such function anyway?


You can use .find() to find the nested option.

var SelectElement = $('#SelectElementId');
var ValueOfSelected = SelectElement.find('option:selected').val();

...but because it is a select element, you can just use the val()[docs] method directly.

var SelectElement = $('#SelectElementId');
var ValueOfSelected = SelectElement.val();

This will give you the value of the selected option.


The result of a JQuery selector, in this case "SelectElement" can be accessed through out the rest of the script. You dont need to use the JQuery Selector "$()" a second time.


var select_element = $('#SelectElementId');
// these two below gives you the same result
var value_of_selected = $('#SelectElementId option:selected').val();
var value_of_selected = select_element.val();

sometimes you don't really have to use reference variables. it's useful if you actually use it multiple times.

0

精彩评论

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