如何使用 jQuery 将函数绑定到所有输入元素?
假设我有这套 HTML 标记和 CSS
#CSS
.inputhelp_text { background: #000; color: #fff; }
.nodisplay { display: none; }
<input class="inputhelp" id="firstname" /><span class="inputhelp_text nodisplay" id="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>
使用 jQuery,我需要将一个函数绑定到所有输入字段(我猜使用 jQuery 的 EACH 函数),这样当我单击输入字段时,它应该切换每个范围的类仅“inputhelp_text”。我已经让它在每个领域的两个单独的函数中工作,但由于我有很多领域,我知道有更好的方法来解决它。
有什么建议吗?
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="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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您想要将处理程序绑定到
blur()
和focus()
事件:通常我建议使用 jQuery 效果,例如
hide()
和show()
但这些仅适用于块级元素。是内联的,所以这不起作用。
You want to bind handlers to the
blur()
andfocus()
events:Normally I'd recommend using jQuery effects like
hide()
andshow()
but these only really work with block level elements.<span>
are inline so this won't work.您可以使用每个函数:
例如,您可以
在回调中使用:。
You can use the each function:
For example you could have:
inside the callback.
在这种情况下我所做的如下。假设您想要以某种方式绑定一组
$("input")
,例如您想要添加一个.invalid
类code> 当它们为空时:通过存储对从
$.fn.each
返回的$(this)
的引用,您现在可以单独绑定到每个元素上的事件。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:By storing a reference to
$(this)
returned from$.fn.each
, you can now bind to events on each of the elements individually.