1

この質問は、クラスを使用した jQuery Character Counterの拡張ですか? .

テキストエリア フィールドに を追加し、data-content="####"jQuery を使用して数値を取り出し、それを文字カウンター リミッターに適用したいと思います。

<textarea id="field1" class="input-xlarge limitChars" data-content="2000" rows="2" name="field1">このフィールドには 2000 文字の制限があります

<textarea id="field2" class="input-xlarge limitChars" data-content="1000" rows="2" name="field2">このフィールドには 1000 文字の制限があります

<textarea id="field3" class="input-xlarge limitChars" data-content="1500" rows="2" name="field3">これは1500文字になります。

私の他の質問の解決策(以下の解決策を参照)から、DOMからデータコンテンツを引き出して、それを目標に適用する必要があると思います。データコンテンツから価値を引き出す方法がわからないので、助けていただければ幸いです。

$(document).ready(function(){
    $(".limitChars").each(function() {
        $(this).counter({
            goal: 500
        });
    });
});

================================================== ===
拡張されたダイアログが表示されたので、実際に最終的にどうなったかを示すと役立つかもしれないと考えました。

HTML

<textarea id="field1" class="input-xlarge" counter-limit="2000" rows="2" name="field1"> this field would have a limit of 2000 chars

JavaScript/jQuery

$("[data-counter-limit]").each(function() {
      var $this = $(this), limit = +$(this).data("counter-limit");
      $this.counter({
        goal: parseInt(limit,10)
        //  goal: limit
      });
});
4

2 に答える 2

2

メソッドを使用して、属性.data()から値を抽出しdata-ます。次にparseInt(string, radix)、それを数値に変換するために使用します

$(document).ready(function(){
    $('.limitChars').each(function() {
        var self = $(this);
        self.counter({
            goal: parseInt(self.data('content'),10)
        });
    });
});
于 2012-12-19T21:51:10.447 に答える
1

クラス名を削除して、属性のみlimit500を直接使用できます。両方を一緒に使用するよりもクリーンです。data-*data-counter-limit

<textarea data-counter-limit="1000">

$("[data-counter-limit]").each(function() {
  var $this = $(this), limit = +$(this).data("counter-limit");
  $this.counter({
    goal: limit
  });
});

セレクター[data-counter-limit]は、属性を持つすべての要素を取得しますdata-counter-limit。残りは、制限を解析して要素を処理することです。

于 2012-12-19T21:53:30.133 に答える