我有这个HTML
<div class="form-new"><input name="a1" /></div>
<div class="form-new"><input name="a2" /></div>
<div class="form-new"><input name="a4" /></div>
<div class="form-new"><input name="a3" /></div>
...
它是动态的,所以我想用jquery在输入名称末尾得到最大数字(在这个例子中,它将是a4),请告诉我如何做到这一点,对不起我的坏英语
答案 0 :(得分:2)
var maxVal = -1; // set to the minimum possible value
var maxInput;
$('.form-new input').each(function (i, e) {
var val = parseInt($(e).attr('name').match(/\d+$/)[0]); // gets the number at the end of "name" attribute value
if (val > maxVal) {
maxVal = val;
maxInput = $(e);
}
});
// maxInput holds the jQuery object of the input with max value at the end of "name" attribute
答案 1 :(得分:1)
这是一个可能的解决方案:
对div中的值进行排序并显示最后一个值。
var inputList = $('input').sort(function (a, b) {
var contentA =$(a).attr('name');
var contentB =$(b).attr('name');
return (contentA > contentB);
})
var totalInputItems = inputList.length;
alert($(inputList[totalInputItems-1]).attr('name'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-new"><input name="a1" /></div>
<div class="form-new"><input name="a2" /></div>
<div class="form-new"><input name="a4" /></div>
<div class="form-new"><input name="a3" /></div>
答案 2 :(得分:1)
您可以按照以下方式编写:
<强> DEMO HERE 强>
var ip=$('.form-new input');
var numbers=[];
var maxNum=0;
$.each(ip,function(index,value){
numbers.push([value["name"].split("a")[1],value]); //storing along with control so that you can refer in in future if you want
});
$.each(numbers,function(index,value){
if(value[0]>parseInt(maxNum))
{
maxNum=value[0];
}
});
alert("a"+maxNum);
答案 3 :(得分:1)
Vanilla JS
var largest = [].slice.call(document.querySelectorAll('.form-new')).reduce(function (acc, el) {
var name = el.querySelector('input').getAttribute('name');
return int(name) > int(acc) ? name : acc;
});
function int(s) { return parseInt(~~(s+'').replace(/.*[^\d](\d+)$/g,'$1')); }