1

私のフォームの1つでは、Jqueryを使用して複数の要素を追加できます。次のHTMLは、デモコンテンツを示しています。

<form name="my-location-frm">
    <div class="address">
        <input type="text" name="house-name" value='house1'>
        <input type="text" name="street-no" value='street1'>
    </div>

    <div class="address">
        <input type="text" name="house-name" value='house2'>
        <input type="text" name="street-no" value='street2'>
    </div>

    <div class="address">
        <input type="text" name="house-name" value='house3'>
        <input type="text" name="street-no" value='street3'>
    </div>

    <input type="submit">
</form>

ここでclass="address"ラッパーは何度も繰り返されます。Jqueryを使用して各要素(house-name、street-no)の値を取得する方法

次のように試しました、

$.each($(".address"), function(key,value) { 

     hn = $(value).children("input[name=house-name]").val();
     console.log(n);
}

しかし失敗します:(

期待されるJavascript出力、

house1,street1
house2,street2
house3,street3
4

2 に答える 2

4

代わりにこのバリアントを使用してください。

$(".address").each(function() {
    var house = $(this).children("input[name='house-name']").val();
    var street = $(this).children("input[name='street-no']").val();
    console.log(house + "," + street);
});

または (必要に応じて) 配列内のすべての入力値を収集できます。

$(".address").each(function() {
    var values = [];
    $(this).children("input").each(function() {
        values.push(this.value);
    });
    console.log(values.join(","));
});

デモ: http://jsfiddle.net/PtNm5/

于 2012-05-07T10:05:34.340 に答える
1
$.each($(".address"), function(key,value) { 
     var hn = $(this).children('input[name="house-name"]').val(),
         sn = $(this).children('input[name="street-no"]').val();
     console.log(hn.concat(', ' + sn));
});

また

 $.each($(".address"), function(key,value) { 
         var hn = $('input[name="house-name"]', this).val(),
             sn = $('input[name="street-no"]', this).val();
         console.log(hn.concat(', ' + sn));
    });

また

$.each($('.address'), function() {
  var output = $('input[name="house-name"]', this).val().concat(', ' + $('input[name="street-no"]', this).val());
  console.log(output);
});
于 2012-05-07T10:05:20.383 に答える