2012-07-15 135 views
2

我有看起来像“1个回复和30个提到”或“3个回复和1个提及”(显然具有不同数字)的锚文本。我试图用jQuery来替换锚文本添加的数字。jQuery在字符串中添加数字

$(document).ready(function() { 
$('header div.comments-link a').each(function(index) { 
    var myreaction = $(this).text().split(" "); 
    $(this).text(myreaction[0]+myreaction[3]); 
}); 
}); 

因此,对于第一个例子,这将是1 + 30使文本替换将是31.对于第二个例子中,这将是3 + 1,因此文本替换将是4。

然而,它似乎并没有取代实际的文字,似乎也没有正确地分割数组。随着页面的进入,它有时会抓取“1”,但其他时间会抓取“回复”。

任何想法?

+0

你能告诉我们一些HTML或作出[的jsfiddle(http://www.jsfiddle.net)? – Conner 2012-07-15 04:25:45

回答

3

我想尝试一个正则表达式和解析数字字符串转化为实际的整数:

var myreaction = $(this).text().match(/(\d+) Repl(?:y|ies) and (\d+) Mention(?:s?)/); 
$(this).text(parseInt(myreaction[1], 10) + parseInt(myreaction[2], 10)); 
+0

这与“答复”或“提及”不符。 – Inkbug 2012-07-15 04:57:37

+0

它现在应该.. – Blender 2012-07-15 04:59:49

+0

证明它的工作原理(稍作修改,使小提琴变得容易):http://jsfiddle.net/pGH6p/ Upvoted,但作为一个人,仍然没有成为流利的正则表达式,并知道其他开发人员谁也不是,对我来说看起来像是希腊人。知道我并不孤单,让我怀疑正则表达式是一种可维护的解决方案。 – 2012-07-15 05:09:21

2

工作演示http://jsfiddle.net/BxUXX/1/

对于添加2使用parseInt

希望它有助于

代码

var str = "1 Reply and 30 Mentions"; 

$(document).ready(function() { 
    // $('header div.comments-link a').each(function(index) { 
     var myreaction = str.split(" "); 
     alert(parseInt(myreaction[0]) + parseInt(myreaction[3])); 
    // }); 
});​ 
+0

作为一个傻笑(阅读:我没有真正优化代码)我采取了这个想法,并扩大它,所以你不必寻找具体的myreaction指数:http://jsfiddle.net/BxUXX/3/ – 2012-07-15 04:59:07

+1

@GregPettit哈哈哈哈 - 哈哈':''你在ICFP 2012年 - 人变得越来越热!我会保持你的jsfiddle分享':)' – 2012-07-15 05:02:29

+0

不,我不是。一定要保持你的衬衫。 ;) – 2012-07-15 05:12:28

0

试试这个:

$(document).ready(function() { 
    $('header div.comments-link a').each(function(index) { 
    var s = $(this).text().replace(/\D/g, "").split("") 
    $(this).text(parseInt(s[0], 10) + parseInt(s[1], 10)); 
    }); 
});