admin管理员组文章数量:1389903
I have something like this:
<div id="row1">Some content</div>
<div id="row2">Some content</div>
<div id="row3">Some content</div>
<div id="row4">Some content</div>
<div id="row7">Some content</div>
<div id="row15">Some content</div>
<div id="row915">Some content</div>
<div id="row919">Some content</div>
Rows are actually pulled from PHP array and now I need to extract last row's number e.g. in this case that would be 919. (so I can add +1 to row id when I use append to generate more rows via jQuery).... Any ideas ?
I have something like this:
<div id="row1">Some content</div>
<div id="row2">Some content</div>
<div id="row3">Some content</div>
<div id="row4">Some content</div>
<div id="row7">Some content</div>
<div id="row15">Some content</div>
<div id="row915">Some content</div>
<div id="row919">Some content</div>
Rows are actually pulled from PHP array and now I need to extract last row's number e.g. in this case that would be 919. (so I can add +1 to row id when I use append to generate more rows via jQuery).... Any ideas ?
Share Improve this question asked Dec 19, 2012 at 8:15 PeterPeter 1,2965 gold badges20 silver badges41 bronze badges 1-
parseInt(this.id.replace('row',''),10) +1
– adeneo Commented Dec 19, 2012 at 8:19
5 Answers
Reset to default 5Id suggest rather than doing this you keep a variable with the last value. When you then append you can alter this value. This saves getting the id and parsing it.
assuming they're in the same div, and assuming that the row919 is the last element, you can do something like this:
var last_element_id = $('.parentDiv').last().attr('id');
var number = last_element_id.replace('row','');
If you cant do what Jon have suggested you can try this:
var max = -Infinity;
$('div').each(function () {
var match = this.id.match(/^row([0-9]+)$/)
if (max < match[1]) {
max = match[1];
}
});
$('#row' + max).html('Max!');
Here is an example fiddle: http://jsfiddle/HTkkb/
The script above finds the maximum number for postfix of all div's ids and gets the element with id row + max
Use :last
alert($('div:last').attr('id').split('row')[1]);
Fiddle example jsfiddle
It easier to use the data-
attribute and a class:
<div class="row" data-id="1">Some content</div>
<div class="row" data-id="2">Some content</div>
As the other answers have said, storing a variable and incrementing would be better to get the next increment. However you should still consider the data-id structure and not trying to parse it out of the id attribute which has a label wihthin it.
本文标签: javascriptJquery get latest id of element and extract the numberStack Overflow
版权声明:本文标题:javascript - Jquery get latest id of element and extract the number - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744636276a2616840.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论