I have a JQuery code which does something when input or select ele开发者_如何学编程ments get focus. Although my code for input element works, select element does not work.
Here is what I do.
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(":input").focus(function () { //this works
//do something
});
$(":select").focus(function () { //this doesn't
//do something
});
});
</script>
</body>
I tried some variation on select, such as using $("select") instead of $(":select"), but did not work either.
I am a beginner for JQuery.
I appreciate if you could tell me how I can make it work.
Thanks a lot!
Short and simple: Because :select
does not exist.
$('select')
will work, but only if you have a <select>
element in your code. You have not in your above code.
Have a look at the list of selectors.
:input
instead does exist:
Selects all input, textarea, select and button elements.
In general: Selectors starting with a colon :
are pseudo selectors. They are defined by jQuery (they are not valid CSS selectors) and select elements with a certain state or property).
You already have encountered :input
. It selects all form control elements. Another one is e.g : visible
, which selects all displayed (visible) elements.
Update:
The <select>
elements have to exists when $('select').focus(...
is executed. I don't know the software you are using, but if they load the elements e.g. via Ajax, then most likely they don't exist yet when your code is executed.
- Make sure there are
<select>
elements on the page. You might have to use
.live()
:$('select').live('focus', function() { //stuff });
There isn't a :select selector, but since "select" is its own tag in HTML, you can just use $('select') (like you can use $('body'), for example). A better approach is probably to assign an "id" to your "select" element, and then use $('#id') to select that element directly.
$(":select") is not a valid selector. http://api.jquery.com/category/selectors/
You should avoid using :input :select alone. This is a performance killer specially if you have allot of elements in your DOM. :input means jQuery must search every elements in your DOM to find inputs. The below selector is allot faster and more efficient.
$('#myform').find('input')
Check performance test (75% faster) http://jsperf.com/input-selector-performance0
So you can basically do
$('#myform').delegate('select','focus', function() {
// what ever you want to do here
});
精彩评论