HTML 代码:
<div id="block-id-45"></div>
我怎样才能得到号码"45"字符串使用jQuery http://en.wikipedia.org/wiki/JQuery?
To 返回末尾的数字id
属性 use
$(this).attr("id").match(/[\d]+$/);
上面会返回45
if $(this)
is <div id="block-id-45"></div>
jsFiddle 示例 http://jsfiddle.net/cxLuK/
上面的工作方式是使用以下命令检索元素的 id.attr() http://api.jquery.com/attr/,然后你看id
并使用.match() https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match恢复其末尾的数字。/[\d]+$/
是一个正则表达式。[\d]
表示一位数字+
表示一个或多个(数字)。和$
意味着该行的末尾。
您可以使用此函数从 id 以 开头的所有 div 末尾检索数字block-id-
通过利用属性以选择器开头[name^=value] http://api.jquery.com/attribute-starts-with-selector/ and .each() http://api.jquery.com/jQuery.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 示例 http://jsfiddle.net/3V5CG/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)