0

以下のコードを使用して、UI でユーザーが入力した値をフェッチしようとしています

$.each($('item'), function(i, v) {
  var test = new Object();
  test.attribute = $("#Attribute_" + i).val();
  test.operand = $("#Operand_" + i).val();
  test.value = $("#Value_" + i).val();
});

私のHTMLコード

<div class="item">
    <input id="Attribute_0" name="Attribute_1" type="text">
    <select id="Operand_0">
    <input id="Value_0" type="text">
</div>

    <div class="item">
        <input id="Attribute_1" name="Attribute_1" type="text">
        <select id="Operand_1">
        <input id="Value_1" type="text">
    </div>

ID が 0 で始まる限り、すべて正常に動作します(Attribute_0,Operand_0).

ただし、1 以上で始まる場合、.each i 値は 0 で始まるため、上記の関数は機能しません。

HTMLが次のように始まる場合

 <div class="item">
                <input id="Attribute_1" name="Attribute_1" type="text">
                <select id="Operand_1">
                <input id="Value_1" type="text">
            </div>

そしてNullを取得しています

値をフェッチする方法は他にもたくさんあるかもしれませんが、現在私はこれを実装しており、いくつかの変更を加えて同じコードに固執したいと考えています。

どうすればこれを処理できますか?

ありがとう

4

3 に答える 3

3

ID の代わりにクラスを使用するように HTML を変更します。

<div class="item">
    <input class="attribute" name="Attribute_1" type="text">
    <select class="operand">
    <input class="value" type="text">
</div>

次に、クラス セレクター +.childrenを使用して、 current 内の要素への参照を取得します.item

$('.item').each(function() {
  var $this = $(this);
  var test = {
    attribute: $this.children('.attribute').val(),
    operand: $this.children('.operand').val(),
    value = $this.children('.value').val()
  };
});

または、フォーム要素の順序が常に同じ (属性、オペランド、値) である場合は、(クラスや ID を使用せずに) 位置によって子にアクセスできます。

$('.item').each(function() {
  var $children= $(this).children();
  var test = {
    attribute: $children.eq(0).val(),
    operand: $children.eq(1).val(),
    value = $children.eq(2).val()
  };
});
于 2013-05-16T07:50:17.450 に答える
2

マークアップを変更したくない場合は、これでうまくいくはずです。「属性で始まる」セレクターについては、jQuery のドキュメントを参照してください。

$('.item').each(function() {
  var $this = $(this),
      test  = {
        attribute : $this.find('[id^="Attribute_"]').val(), 
        operand   : $this.find('[id^="Operand_"]').val(),
        value     : $this.find('[id^="Value_"]').val()
      };
});

JSFiddle

于 2013-05-16T07:49:43.353 に答える