jQuery从动态标签获取属性

jQuery get attribute from dynamic tag

本文关键字:获取 属性 标签 动态 jQuery      更新时间:2023-09-26

我有这个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),请告诉我如何做到这一点,抱歉我的英语不好

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

这是一个可能的解决方案:

对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>

你可以这样写:

演示

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);

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')); }

http://jsfiddle.net/j91x5asd/8/