[英]How to get a min/max int value from string?
I have a many elements in page whis id = "item(\\d{1,})"
. 我在页面中有很多元素,如下所示:'
id = "item(\\d{1,})"
。 How to quickly get element id with a min value and max value of (\\d{1,})
regexp ? 如何使用最小值和最大值
(\\d{1,})
regexp快速获取元素id?
Use this to get list of your IDs: 使用它来获取您的ID列表:
$j("[id^=item]").map(function(){ return Number(this.id.substr(4)); });
I don't think jQuery has any tools to quickly get min/max value, but it is pretty trivial to write yourself. 我不认为jQuery有任何工具可以快速获得最小/最大值,但写自己是非常简单的。
As per Vivin's request providing the trivial part: 根据Vivin的要求提供了琐碎的部分:
var arr = $j("[id^=item]").map(function(){ return Number(this.id.substr(4)); }).sort();
var min = arr[0];
var max = arr[arr.length-1];
You can also use querySelectorAll
if the browser supports it; 如果浏览器支持,您也可以使用
querySelectorAll
; all browsers should select it. 所有浏览器都应该选择它。 IE has supported it since 8.
IE从8开始就支持它。
var elements = document.querySelectorAll("[id^=item]");
var max = null;
var min = null;
for(var i = 0; i < elements.length; i++) {
var number = elements[i].id.replace(/item/, "");
if(max == null) {
max = number;
min = number;
}
else {
max = (number > max) ? number : max;
min = (number < min) ? number : min;
}
}
If the browser doesn't support it, you would have to do something like this: 如果浏览器不支持它,您必须执行以下操作:
//assuming that you're looking for div; just replace it with the actual element
//you're looking for
var elements = document.getElementsByTagName("<div">);
var max = null;
var min = null;
for(var i = 0; i < elements.length; i++) {
if(/item\d+/.test(elements[i].id)) {
var number = elements[i].id.replace(/item/, "");
if(max == null) {
max = number;
min = number;
}
else {
max = (number > max) ? number : max;
min = (number < min) ? number : min;
}
}
}
Or if you're using jQuery: 或者如果你正在使用jQuery:
var max = null;
var min = null;
jQuery("[id^=item]").each(function() {
var number = this.id.replace(/item/, "");
if(max == null) {
max = number;
min = number;
}
else {
max = (number > max) ? number : max;
min = (number < min) ? number : min;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.