jQuery:从ID获取号码 [英] Jquery: Getting the number from ID

查看:63
本文介绍了jQuery:从ID获取号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您在另一个问题中提到了此问题: jquery从id获取编号

You mentioned this in another question: jquery get number from id

您应该养成在属性名称(即button-1,button_1)中使用定界符的习惯.许多优点之一是,它使从字段中提取数字或其他信息变得更加容易(例如,通过在'-'处拆分字符串).

You should get in the habit of using delimiters in your attribute names (ie, button-1, button_1). One of the advantages, of many, is that it makes it easier to extract a number, or some other information, from the field (ie, by splitting the string at '-').

如果在属性名称中使用定界符,您将如何提取数字?

How would you extract the number if you are using a delimiter in your attribute names?

谢谢!

推荐答案

  1. .attr('id')可用于检索ID属性.
  2. 然后,使用.split函数用分隔符分隔字符串.
  3. 从索引[1]获取编号.
  1. .attr('id') can be used to retrieve the ID attribute.
  2. Then, use the .split function to split the string by a separator.
  3. Get the number from index [1].

代码:

 var delimiter = '-';
 var num = $("element").attr('id').split(delimiter)[1];
 // Expected format: <anything 1>-<anything 2>
 // Note that <anything 2> is not necessarily a number

以前的方法非常依赖于id格式.一个更可靠的方法是regexp:

The previous method is very dependent on the id format. A more solid method is a regexp:

var num = /\d+/.exec($("element").attr('id')); // Selects all consecutive digits
// Examples:
//  button_1 = 1    button2 = 2     1st = 1     button4--5 = 4

要匹配末尾的数字,请使用:

To match the digits at the end, use:

var num = /\d+(?=\D*$)/.exec($("element").attr('id'));

这篇关于jQuery:从ID获取号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆