【问题标题】:Javascript function in td element with passing parameter带有传递参数的 td 元素中的 Javascript 函数
【发布时间】:2015-04-30 11:31:13
【问题描述】:

我有以下 <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 中执行此操作。

【问题讨论】:

标签: javascript php html web parameter-passing


【解决方案1】:

缩短方法(可以将提取索引作为参数传递):

/* 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 缩短页面上每个 &lt;td&gt; 元素的 &lt;span&gt; 内的文本:

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);
}

DEMO

或使用 jQuery:

$('td span').each(function(){
    $(this).text(shorten($(this).text()));
});

DEMO

注意: 确保每个&lt;span&gt; 元素都具有唯一 id

【讨论】:

    猜你喜欢
    • 2011-09-15
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    相关资源
    最近更新 更多