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」のみに切り替わります。これは、フィールドごとに 2 つの別々の関数で動作するようになりましたが、多くのフィールドがあるため、それを解決するためのより良い方法があることがわかっています。

助言がありますか?

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()通常は、 や などのjQuery エフェクトを使用することをお勧めしshow()ますが、これらは実際にはブロック レベルの要素でのみ機能します。<span>インラインであるため、これは機能しません。

于 2010-03-23T08:58:14.827 に答える
1

each 関数を使用できます。

$("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)から返された への参照を格納すること$.fn.eachで、各要素のイベントに個別にバインドできるようになりました。

于 2013-02-21T00:14:38.037 に答える