jQuery jquery从id中获取数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2427853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:29:57  来源:igfitidea点击:

jquery get number from id

jquerygetnumbers

提问by john morris

how can i get the number from a div tag's id?

如何从 div 标签的 id 中获取数字?

example:

例子:

<div id="button1"></div>

how can i get the 1 and store it in a variable?

我怎样才能得到 1 并将它存储在一个变量中?

回答by Konrad Garus

var id = $("div").attr('id').replace(/button/, '');

回答by Pointy

Your "id" values cannot be purely numeric; they need to start with a letter or "_" like an identifier. (Note: that's not true in HTML5 documents.) Once you've got a number in your "id" value like that, you would just use the jQuery attr()function to get the id:

您的“id”值不能是纯数字;它们需要以字母或“_”开头,例如标识符。(注意:这在 HTML5 文档中并非如此。)一旦您的“id”值中有这样的数字,您就可以使用 jQueryattr()函数来获取 id:

 var theId = parseInt($('div.whatever').attr('id').replace(/[^\d]/g, ''), 10);

回答by karim79

// replace all non-digits with nothing
alert($('div').attr("id").replace(/\D/g,''));

If you like, you can just grab the numbers at the end:

如果你愿意,你可以在最后获取数字:

// <div id="_34_foo_555"></div>
alert($('div').attr("id").match(/\d+$/));
// alerts "555"

回答by Gumbo

If buttonis a constant prefix, you can do this:

如果button是一个常量前缀,你可以这样做:

var number = parseInt(element.id.match(/^button(\d+)$/)[1], 10);

回答by John Himmelman

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 '-').

您应该养成在属性名称中使用分隔符的习惯(即 button-1、button_1)。许多优点之一是它可以更容易地从字段中提取数字或其他一些信息(即,通过在“-”处拆分字符串)。

回答by Heretic Monkey

This is an old question, but I'd like to add the idea of using a data-attribute rather than encoding information in an id:

这是一个老问题,但我想添加使用data-属性而不是在 id 中编码信息的想法:

window.onload = function() {
  var element = document.getElementById('button1');
  var number = parseInt(element.getAttribute('data-index'), 10);
  console.log(number);
}
<button id="button1" data-index="1"></button>

This way you don't need to go through all of the matching and whatnot.

这样你就不需要经历所有的匹配和诸如此类的事情。