jQuery,从id中选择数字,比如“article-23”

jQuery, selecting just number from id like "article-23"

本文关键字:比如 数字 article-23 选择 id jQuery      更新时间:2023-09-26

好的,我有一个div标签,它有一个class="blog-post"和id,如id="article-23"(其中"23"可以是任何数字,因为它是数据库中博客文章的id)。我需要从id中获取一个数字然后对这个div标签应用一些规则。所以说:

if number from id % 2 == 0 {
  set text colour black to associated div tag with class of blog-post
} else {
  set text colour white to associated div tag with class of blog-post
}

这只是一个"伪"代码来显示逻辑,我不想应用依赖于如果数字从id是偶数或奇数,但问题仍然是一样的,我如何从id像"article-23"获得数字?

就像

var number = "article-23".match(/'d+/)[0];

但是你必须确保字符串中存在任何数字,否则你会得到一个错误

您实际上可以通过函数应用规则,这使得这是最干净的解决方案(在我看来):

$(".blog-post").css('color', function () {
    return +this.id.replace('article-', '') % 2 ? 'blue' : 'red';
});
http://jsfiddle.net/ExplosionPIlls/Jrc5u/

试试这个:

$('.blog-post[id^="article-"]').each(function () {
    if (parseInt(this.id.replace('article-', '')) % 2 === 0) {
        $('#' + this.id).css('color', 'black');
    } else {
        $('#' + this.id).css('color', 'white');
    }
});

jsFiddle演示

作为替代方案,HTML5支持这些被称为"数据属性"的东西,这是专门用于将数据附加到DOM而不会滥用"class"或"id"属性之类的东西。jQuery提供了一个方便的.data方法,以更明显的方式读取这些属性。

你可以添加你自己的数字ID属性,比如"data-id":

<div class="blog-post" data-id="23" />
$("#blog-post").each(function () {
  console.log($(this).data("id")); // Look up the data-id attribute
});

如果我理解正确的话,您需要的是.blog-post类的id标记的连字符之后的数字。

var article = $(".blog-post").attr('id'); //get the id
var article = article.split("-");  // split it on hyphens
return article = article[article.length-1];  // return the last element