【问题标题】:JavaScript/JQuery string replaceJavaScript/JQuery 字符串替换
【发布时间】:2010-07-07 15:21:32
【问题描述】:

我有以下字符串,它是一个 CSS 选择器:

#downloads > ul > li:nth-of-type(1) > ul > li:nth-of-type(3) > a

此 CSS 选择器在 FireFox、CHrome 和 Safari 中运行良好,但 IE 6 不支持 nth-of-type 选择器。我正在使用的 CSS 选择器是由 Nokogiri 生成的,我无法更改它们。

Threw 测试我已经完成了以下工作:

#downloads > ul > li:nth(0) > ul > li:nth(2) > a

将第 n 个选择器更改为普通的第 n 个并从第 n 个值中减去一个。我一直在尝试使用 JS 以编程方式将 CSS 选择器从使用 nth-of-type 转换为普通 nth?所以运行后就扔了:

#downloads > ul > li:nth-of-type(1) > ul > li:nth-of-type(3) > a

会变成

#downloads > ul > li:nth(0) > ul > li:nth(2) > a

干杯

伊夫

【问题讨论】:

标签: javascript jquery css regex css-selectors


【解决方案1】:

Javascript

var str = "#downloads > ul > li:nth-of-type(1) > ul > li:nth-of-type(3) > a";
str = str.replace(/:nth-of-type\(([0-9]+)\)/g, function(match, first) {
   return ":nth(" + (parseInt(first)-1) + ")";
});

alert(str); // -> #downloads > ul > li:nth(0) > ul > li:nth(2) > a

[See it in action]

【讨论】:

    猜你喜欢
    • 2011-09-04
    • 2016-02-21
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    相关资源
    最近更新 更多