要返回 id
属性末尾的数字,请使用:
$(this).attr("id").match(/[\d]+$/);
如果$(this)
是<div id="block-id-45"></div>
,上面的代码将返回45
以上代码的工作原理是使用.attr()
检索元素的id,然后查看id
并使用.match()
恢复其末尾的数字。/[\d]+$/
是一个正则表达式。 [\d]
表示一个数字,+
表示一个或多个(数字),而$
表示行的结尾。
[name^=value]
和.each()
来获取所有以block-id-
开头的div标签末尾的数字:
$(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/>" );
});
});
对于这个问题,您不需要(或特别想要)使用jQuery(它非常适用于许多其他事情,但对于这个问题来说并不是特别必要的)。可以使用纯JavaScript和DOM操作:
var div = document.getElementById('block-id-45');
var n = div.id.lastIndexOf('-');
var target = div.id.substring(n + 1);
实时示例: http://jsbin.com/osozu
如果您已经在使用jQuery,您可以将第一行替换为:
var div = $('#block-id-45')[0];
...但是几乎没有任何理由这样做。
block-id-
。 - Peter Ajtai