Vla*_*adY 8 string jquery substring
HTML代码:
<div id="block-id-45"></div>
Run Code Online (Sandbox Code Playgroud)
如何使用jQuery获取字符串的数字"45"?
Pet*_*tai 31
要在id属性使用结束时返回数字
$(this).attr("id").match(/[\d]+$/);
Run Code Online (Sandbox Code Playgroud)
45如果$(this)是,上面将返回<div id="block-id-45"></div>
上面的工作方式是你使用了检索元素的id .attr(),然后你看看id并使用它.match()来恢复它的末尾的数字./[\d]+$/是一个正则表达式.[\d]表示一位数+表示一个或多个(数字).并且$意味着该行的结束.
您可以使用此函数从所有div的末尾检索数字,其id block-id-通过使用以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/>" );
});
});?
Run Code Online (Sandbox Code Playgroud)
你不需要(或者特别想要)jQuery(它对很多其他东西非常有用,对此并不特别).直接的JavaScript和DOM:
var div = document.getElementById('block-id-45');
var n = div.id.lastIndexOf('-');
var target = div.id.substring(n + 1);
Run Code Online (Sandbox Code Playgroud)
如果您已经在使用jQuery,则可以将第一行替换为:
var div = $('#block-id-45')[0];
Run Code Online (Sandbox Code Playgroud)
......但是几乎没有任何理由.