最佳答案
返回 id
末尾的数字属性使用
$(this).attr("id").match(/[\d]+$/);
以上将返回 45
如果$(this)
是 <div id="block-id-45"></div>
上面的工作方式是使用 .attr()
检索元素的 id ,然后你看id
并使用 .match()
恢复其末尾的数字。 /[\d]+$/
是一个正则表达式。 [\d]
表示一位数字 +
表示一个或多个(数字)。和$
表示行尾。
您可以使用此函数检索 id 以 block-id-
开头的所有 div 末尾的数字。通过使用 attribute starts with selector [name^=value]
和 .each()
:
实际用法:
$(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/>" );
});
});
<强> jsFiddle example
关于jquery - 使用 jQuery 获取字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3722360/