我有以下html:
<button type="button" id="step-1">step1</button>
<button type="button" id="step-2">step2</button>
<button type="button" id="step-3">step3</button>
<button type="button" id="step-4">step4</button>我想从id中获取数字,比如1,2,3,4。所以像这样使用:
$('[id^=step]').on('click',function(){
var stepbg = parseInt($(this).attr('id'),10);alert(stepbg);
});但这引起了NaN的注意。demo
发布于 2014-04-03 13:23:46
您可以使用split()实现这一点
$('[id^=step]').on('click',function(){
var stepbg = parseInt($(this).attr('id').split("-")[1],10);alert(stepbg);
});你也可以使用replace函数
$('[id^=step]').on('click',function(){
var stepbg = parseInt($(this).attr('id').replace('step-','')); alert(stepbg);
});下面是另一个正则表达式示例
$('[id^=step]').on('click',function(){
var stepbg = parseInt($(this).attr('id').match(/\d+$/)[0], 10); alert(stepbg);
});发布于 2014-04-03 13:22:30
尝试使用简单的正则表达式从id中提取最后一组数字
var stepbg = parseInt(this.id.match(/\d+$/)[0], 10);演示:Fiddle
发布于 2014-04-03 13:23:05
在jquery中使用split()。
$('[id^=step]').on('click',function(){
var stepbg = parseInt($(this).attr('id').split("-")[1] ,10);
alert(stepbg);
});Fiddle
https://stackoverflow.com/questions/22828474
复制相似问题