jQuery从动态标签获取属性
jQuery get attribute from dynamic tag
我有这个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/
相关文章:
- 无法获取属性'selectedIndex'的未定义引用或null引用
- 如何从选择框中的选项中获取属性值
- 无法获取属性'Id'使用Knockout.js的未定义或空引用API
- 使用Undercore获取属性值数组
- Microsoft JScript运行时错误:无法获取属性'的值;样式':对象为null或未定义
- "无法获取属性'的值;style'"当试图在IE中更改样式时
- 无法获取属性'字符串'的未定义或null引用IE 11 ASP.NET
- 无法获取属性'的值;拆分'在IE8中调用ajax之后
- JQuery关键字“;这个“;未获取属性值
- SCRIPT5007:无法获取属性'长度'的未定义引用或null引用
- 为什么我得到“;无法获取属性的值'SetReturnValue'"当使用ceebox显示YouT
- 无法获取属性'setActionableButtonState'的未定义引用或null引用
- JavaScript |对象:获取属性忍者移动
- 如何使用 jQuery 在循环中获取属性的值
- 无法获取属性'偏移'的未定义引用或null引用
- 从列表中的选定项获取属性值
- 获取属性(邮政编码)并在Google地图API 3中使用
- IE:无法获取属性'的值;clientWidth':对象为null或未定义
- 如何通过类名和过滤函数获取属性值
- 无法使用javascript表示法获取属性值