2

HTML のフォームがあり、javascript を使用してフィールドから最大数を抽出したいと考えています。例えば:


<input id="temp_0__Amount" name="temp[0].Amount" type="text" value="lorum ipsum">
<input id="temp_1__Amount" name="temp[1].Amount" type="text" value="lorum ipsum">
<input id="temp_2__Amount" name="temp[2].Amount" type="text" value="lorum ipsum">

この場合、javascript で 2 を生成する必要があります。

私はjQueryで何かを試していましたが、それ以上はできません:

$('input[name^="temp"]').last().name;

これにより、 が生成されtemp[2].Amountます。しかし、私は2を抽出したいだけです。文全体ではありません。そして、部分文字列のようなものを使用できることは知っていますが、「クリーンな」方法があるかどうか疑問に思いました。

4

5 に答える 5

4
var max = Math.max.apply(Math, $('input').map(function(){
      return this.name.match(/\d+/);
}).get());

console.log(max);

http://jsfiddle.net/fmpw3/

于 2013-03-09T16:22:47.757 に答える
0

2番だけを抽出したい場合:

$('input[name^="temp"]').size()-1;
于 2013-03-09T16:22:43.093 に答える
0

ここで data- 属性を使用します:-

<input id="temp_0__Amount" name="temp[0].Amount" data-amount="0" type="text" value="lorum ipsum">
<input id="temp_1__Amount" name="temp[1].Amount" data-amount="1" type="text" value="lorum ipsum">
<input id="temp_2__Amount" name="temp[2].Amount" data-amount="2"  type="text" value="lorum ipsum">

jqueryで値を取得できます:-

 var amount = $('input[name^="temp"]').last().data('amount');

ライブ デモはこちらライブ デモ リンク

于 2013-03-09T16:22:43.110 に答える
0

少し派手な(もう1つの解決策):

var max = $('input').map(function(){
   return this.name.match(/\d+/);
}).get().sort().reverse()[0];

http://jsfiddle.net/wSmEV/

于 2013-03-09T16:27:00.800 に答える
0

試す:

var lastName = $('input[name^="temp"]').find(":last").prop("name"),
    amount = lastName.replace(/^temp\[|\]\.Amount/g,'');
于 2013-03-09T16:34:21.633 に答える