what is the equivalent of this javascript in Jquery
How do we write Equivalent value of this in Jquery
document.getElementById( "selectbox").
options[docum开发者_StackOverflow中文版ent.getElementById("selectbox").selectedIndex].innerText;
Simple:
$('#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...
精彩评论