1

假设我有这套 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”。我已经让它在每个字段的两个单独的函数中工作,但由于我有很多字段,我知道有更好的方法来解决它。

有什么建议么?

4

3 回答 3

2

您想将处理程序绑定到blur()focus()事件:

$(".inputhelp").focus(function() {
  $("span.inputhelp_text:visible").addClass("nodisplay");
  $(this).next("span.inputhelp_text").removeClass("nodisplay");
}).blur(function() {
  $("span.inputhelp_text").addClass("nodisplay");
});

hide()通常我会推荐使用像and这样的 jQuery 效果,show()但这些效果只适用于块级元素。<span>是内联的,所以这不起作用。

于 2010-03-23T08:58:14.827 回答
1

您可以使用每个功能:

$("input").each(function() {
  // this points to the input DOM element
  // $(this) is the jQuery wrapped element
});

例如,您可以:

$(this).removeClass("inputhelp");
$(this).addClass("inputhelp_text");

回调里面。

于 2010-03-23T08:53:56.660 回答
0

我在这种情况下所做的如下。假设您有一组$("input")要以某种方式绑定的 ',例如,您想.invalid在它们为空时添加一个类:

$("input").each(function () {
      var $this = $(this);
      $this.focus(function (e) {
        $this.removeClass("invalid");
      });

      $this.blur(function (e) {
        if ($this.val() == "") {
          $this.addClass("invalid");
        }
      });
    });

通过存储对$(this)返回 from的引用$.fn.each,您现在可以单独绑定到每个元素上的事件。

于 2013-02-21T00:14:38.037 回答