[英]How can I apply CSS only to digits in jQuery?
I have this html 我有这个HTML
<tr>
<td>Test</td>
<td>324</td>
</tr>
My default CSS is text-align:left
我的默认CSS是
text-align:left
But I want to apply text-align:center
to any <td>
that contains digits. 但是我想将
text-align:center
应用于任何包含数字的<td>
。
I have about 50 HTML files so I can't add class manually. 我大约有50个HTML文件,因此无法手动添加类。
You could use filter
and some regex magic: 您可以使用
filter
和一些正则表达式魔术:
$('td').filter(function() {
return /^\d/.test($(this).text());
}).css('text-align', 'center');
The above regex is a bit simple, if you need more precision use this one: 上面的正则表达式有点简单,如果您需要更高的精度,请使用此正则表达式:
/((?!\w+[^\s]))\d+\1/
The above will match (space)123
and 123(space)
but not 123a
or asd 123
so basically only numbers and spaces allowed if that's what you're looking for. 上面的将匹配
(space)123
和123(space)
但不匹配123a
或asd 123
因此,如果您要查找的是基本上只允许数字和空格。 To add more valid characters just put them like [^\\s,]
, that will make the comma ,
valid too. 要添加更多的有效字符只是把他们像
[^\\s,]
,这将使逗号,
有效了。
old-school solution (works well): 老式的解决方案(效果很好):
function Trim(str){
return str.replace(/^\s+|\s+$/g,"");
}
function applyCssCustomToSomeTds(){
for(i=0;i<document.getElementsByTagName('td').length;i++){
var elementTd = document.getElementsByTagName('td')[i];
if(!isNaN(Trim(elementTd.innerHTML))){
elementTd.style.textAlign = "center";
}
}
}
$(function(){
$("td").filter(function(){
return (/^\s*\d*\.?\d+\s*$/).test(this.innerHTML);
}).css("text-align","center");
});
EDIT: here's a jsfiddle: http://jsfiddle.net/Avf7P/ 编辑:这是一个jsfiddle: http : //jsfiddle.net/Avf7P/
As another example of adding a class through jquery you can check out this fiddle . 作为通过jquery添加类的另一个示例,您可以查看此小提琴 。 The class 'centerMe' just includes the text-align value that you need.
类“ centerMe”仅包含所需的文本对齐值。
$('td').each(function(){
if($.isNumeric($(this).html()))
{
$(this).addClass('centerMe');
}
});
Note that this uses the isNumeric which may not be your intent. 请注意,这使用的isNumeric可能不是您的意图。 If that's the case then you'd need to modify this to use one of the regex approaches mentioned in some of the other solutions.
如果是这种情况,那么您需要对其进行修改,以使用其他一些解决方案中提到的正则表达式方法之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.