根据部分匹配查找div id的值

时间:2012-01-29 05:54:32

标签: javascript jquery

我在页面上有几个div。它们的格式如下:

<div id='profile-1'></div>
<div id='profile-2'></div>
<div id='profile-3'></div>
<div id='profile-4'></div>

我需要找到id最高的div的值。在前面的例子中,它将是“profile-4”(因为4是最高的)。

我已经想出如何使用以下方法搜索div:

var elements = $('[id^=profile-]')

返回一个对象。我需要拿出那个对象并弄清楚“profile-4”是最高的,如果可能的话,提取值“4”。

有什么想法吗?

4 个答案:

答案 0 :(得分:6)

你可以这样做:

var highest = 0;
$('[id^=profile-]').each(function(){
   var id = parseInt(this.id.split('-')[1], 10);
   highest = id > highest ? id : highest;
});

alert(highest); // 4

即使您有不同的订单,这也会有效:

<div id='profile-1'></div>
<div id='profile-20'></div>
<div id='profile-3'></div>
<div id='profile-4'></div>

在这种情况下,20会被警告。

答案 1 :(得分:2)

以下是另一种方法:如果div始终按升序排列(如您提供的HTML代码段中),则可以执行以下操作:

$('div[id^=profile-]').get().reverse()[0]

答案 2 :(得分:1)

@Sarfraz's answer上构建,您可以使用map构建精美混淆的代码:

var highest = Math.max.apply(null, $('[id^="profile-"]').map(function() {
  return [parseInt(this.id.split('-')[1], 10)];
}));

console.log(highest);

答案 3 :(得分:0)

var highest = Math.max.apply(null, $.map($('[id^=profile-]'), function(el) {
    return el.id.split('-')[1];
});)

var highest_div = $('#profile-'+highest);