gpt4 book ai didi

javascript - 计算每个类的长度

转载 作者:行者123 更新时间:2023-11-30 12:59:54 24 4
gpt4 key购买 nike

我在 this fiddle 中也有以下代码.

HTML

    <span class="myName">John Smith</span>
<span class="myName">John Smith</span>
<span class="myName">John Smith</span>
<span class="myName">John Smith</span>
<span class="myName">John Smith</span>
<span class="myName">John Smith</span>

JavaScript

    $('.myName').each(function(){
var text = $(this).html().split(' '),
len = text.length,
test = $(this).val().length,
result = [];
console.log('outside: ' + test);
for( var i = 0; i < len; i++ ) {
result[i] = '<span class="name-'+[i]+'" >' + text[i] + '</span>';
console.log('inside: ' + test);
}
$(this).html(result.join(' '));
console.log('after: ' + test);
});

它为 myName div 中的每个单词添加一个跨度。我想计算每个 div 中的字符数,这样如果名字很长,我可以将名字缩减为 J Smith,例如。

但是如果您查看控制台日志,我尝试在三个不同的地方计算长度,结果总是返回 0?我做错了什么?

最佳答案

zerkms 是对的。你想改变这个:

test = $(this).val().length,

为此:

test = $(this).text().length,

关于javascript - 计算每个类的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17582574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com