简体   繁体   中英

what is the equivalent of this javascript in Jquery

How do we write Equivalent value of this in Jquery

document.getElementById( "selectbox").
options[document.getElementById("selectbox").selectedIndex].innerText;

简单:

$('#selectbox option:selected').text();

You want to selected the selected <option> within the <select id="selectbox"> tag and get its text:

$('#selectbox option:selected').text()

Because the selectbox can't really contain anything but options, you can omit that part:

$('#selectbox :selected').text()

Like this:

$('#selectbox option:selected').text();

To get it on change event, you can do like this:

$('#selectbox').change(function(){
  alert($('option:selected', $(this)).text());
});

The OPs Javascript example is unnecessarily repetitive and complex. It shows plain Javascript in a bad light compared to jQuery when in fact it should be simpler and more concise. This is really not something jQuery should be used for.

document.getElementById('selectbox').value;

Was that so hard? With the element reference stored in a variable it would be as simple as this

selectbox.value;

And For comparison, the jQuery code

$('#selectbox').val();

IMO the plain Javascript is more readable, direct, and certainly more performant.

I would hardly consider this question academic as the example code is so trivial; it does not involve DOM traversal and has no cross browser compatibility issues, which are the main things jQuery was designed to address. So what the point is I'm not really sure...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM