How do I bind functions to all input elements using jQuery?
let's say I have this set of HTML-markup and CSS
#CSS
.inputhelp_text { background: #000; color: #fff; }
.nodisplay { display: none; }
<input class="inputhelp" id="firstname" /><span class="inputhelp_text nodisplay" id=开发者_Python百科"help_firstname">Write in your firstname</span>
<input class="inputhelp" id="lastname" /><span class="inputhelp_text nodisplay" id="help_lastname">Write in your lastname</span>
Using jQuery, I need to bind a function to all input fields (I guess using jQuery's EACH function) so that when I click the input field, it should switch the class of each span to only "inputhelp_text". I've gotten this to work in two separate functions for each field, but since I have alot of fields, I know there's a better way to solve it.
Any suggestions?
You want to bind handlers to the blur()
and focus()
events:
$(".inputhelp").focus(function() {
$("span.inputhelp_text:visible").addClass("nodisplay");
$(this).next("span.inputhelp_text").removeClass("nodisplay");
}).blur(function() {
$("span.inputhelp_text").addClass("nodisplay");
});
Normally I'd recommend using jQuery effects like hide()
and show()
but these only really work with block level elements. <span>
are inline so this won't work.
You can use the each function:
$("input").each(function() {
// this points to the input DOM element
// $(this) is the jQuery wrapped element
});
For example you could have:
$(this).removeClass("inputhelp");
$(this).addClass("inputhelp_text");
inside the callback.
What I do in this situation is the following. Let us say that you have a set of $("input")
's that you want to bind to in some way, for example you want to add a class of .invalid
when they are empty:
$("input").each(function () {
var $this = $(this);
$this.focus(function (e) {
$this.removeClass("invalid");
});
$this.blur(function (e) {
if ($this.val() == "") {
$this.addClass("invalid");
}
});
});
By storing a reference to $(this)
returned from $.fn.each
, you can now bind to events on each of the elements individually.
精彩评论