我有以下<td>
元素,它显示从数据库中检索到的数据,以显示艺术家的追随者。
<td>
<span id="followers">
<? echo empty($artist['Artist']['followers']) ? 'N/A' : number_format($artist['Artist']['followers']);?>
</span>
</td>
有些值非常大,可以达到6位数。我想写一个Javascript函数,它将接受子字符串,并且只显示前3位数字。
如何编写函数并将参数作为值传递:$artist['Artist']['followers']
我可以用PHP来做这件事,但我需要用javascript来做。
缩短方法(可以将提取索引作为参数传递):
/* USAGE:
str - string to truncate;
start - start index, character position in the string, from which the string should start. Deafault: 0;
end - end index, character position in the string, at which the string should end. Deafault: 3;
*/
function shorten(str, start, end){
// use .trim() to remove whitespaces from the string
return str.trim().substring((start !== undefined ? start : 0),(end !== undefined ? end : 3));
}
通过这种方式,您可以使用纯Javascript缩短页面上每个<td>
元素的<span>
内部的文本:
var td = document.getElementsByTagName('td');
// loop through the <td> elements:
for(var i=0; i<td.length; i++){
// find <span> element inside <td>:
var el = td[i].querySelector('span');
// extract <span> text and truncate. Using default start and end indexes in the function:
el.innerText = shorten(el.innerText);
// Using custom start and end indexes (5 characters. Start at 0, end at 5'th character):
//el.innerText = shorten(el.innerText, 0, 5);
}
演示
或者使用jQuery:
$('td span').each(function(){
$(this).text(shorten($(this).text()));
});
演示
注意:确保每个<span>
元素具有唯一id