使用jQuery获取字符串的一部分 [英] Get part of a string using jQuery
本文介绍了使用jQuery获取字符串的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
HTML代码:
<div id="block-id-45"></div>
如何使用 jQuery "45" >?
How can I get number "45" of string using jQuery?
推荐答案
要返回id
属性末尾的数字,请使用
To return the number at the end of an id
attribute use
$(this).attr("id").match(/[\d]+$/);
如果$(this)
是<div id="block-id-45"></div>
以上方法的工作方式是,您使用 .attr()
,然后查看id
并使用
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.
您可以使用 .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/>" );
});
});
这篇关于使用jQuery获取字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文