You don't need (or particularly want) jQuery for this (it's very useful for lots of other things, just not particularly for this). Straight JavaScript and DOM:
var div = document.getElementById('block-id-45');
var n = div.id.lastIndexOf('-');
var target = div.id.substring(n + 1);
$(function() {
// Select all DIS that start with 'block-id-'
// and iterate over each of them.
$("div[id^='block-id-']").each(function() {
// You could push this data to an array instead.
// This will display it.
$("body").append( "Id number: " +
// This is the number at the end
$(this).attr("id").match(/[\d]+$/) +
"<br/>" );
});
});
The way the above works is that you retrieve the id of the element using .attr(), then you look at the id and use .match() to recover the number at the end of it. /[\d]+$/ is a regex. [\d] means one digit + means one or more (of the digits). and $ means the end of the line.
$(function() {
// Select all DIS that start with 'block-id-'
// and iterate over each of them.
$("div[id^='block-id-']").each(function() {
// You could push this data to an array instead.
// This will display it.
$("body").append( "Id number: " +
// This is the number at the end
$(this).attr("id").match(/[\d]+$/) +
"<br/>" );
});
});
发布评论
评论(3)
使用 jQuery,简单地说:
对于所有 block-id-##,您可以使用来自的掩码模式彼得的回答:
Using jQuery, simply:
For all block-id-##, you can use mask pattern from Peter's answer:
为此,您不需要(或特别需要)jQuery(它对于许多其他事情非常有用,但不是特别适合这个)。直接 JavaScript 和 DOM:
实例: http://jsbin.com/osozu
如果您已经在使用 jQuery,您可以将第一行替换为:
...但是几乎没有理由这样做。
You don't need (or particularly want) jQuery for this (it's very useful for lots of other things, just not particularly for this). Straight JavaScript and DOM:
Live example: http://jsbin.com/osozu
If you're already using jQuery, you can replace the first line with:
...but there's little if any reason to.
要返回
id
属性末尾的数字,请使用上面将返回
45
if$(this)
是< strong>jsFiddle 示例
上面的工作方式是使用
.attr()
,然后查看id
并使用.match()
恢复号码结束了。/[\d]+$/
是一个正则表达式。[\d]
表示一位数字+
表示一个或多个(数字)。$
表示行尾。您可以使用此函数通过使用属性以选择器
[name^=value]
和 < 开头a href="http://api.jquery.com/jQuery.each/" rel="noreferrer">.each()
:实际用法:
jsFiddle 示例
To return the number at the end of an
id
attribute useThe above will return
45
if$(this)
is<div id="block-id-45"></div>
jsFiddle example
The way the above works is that you retrieve the id of the element using
.attr()
, then you look at theid
and use.match()
to recover the number at the end of it./[\d]+$/
is a regex.[\d]
means one digit+
means one or more (of the digits). and$
means the end of the line.You can use this function to retrieve the numbers from the end of all divs with an id that starts with
block-id-
by making use of the attribute starts with selector[name^=value]
and.each()
:Practical usage:
jsFiddle example