javascript - 在循环中截断文本的字符
问题描述
我这里有点问题。
我基本上是在 div 中循环项目,以便每个项目都有一个可以使用的键,这样当单击图标时,会出现一个编辑模式并填充所选项目的数据。
这可行,但我想为我的跨度添加功能,<span>{{ $node->comment }}</span>
以便如果文本超过 10 个字符,它将用 '***' 替换 10 个字符之后的所有内容。我已经尝试通过添加来实现这一点,element.innerHTML = getValue.substring(0 ,4) + ' *** '
但它不起作用并且它忽略了使用密钥的功能。
有没有办法替换文本字符并保留循环/键功能?
@foreach($nodes as $key => $node)
<div class="uk-width-1-1">
<div class="uk-grid uk-grid-small">
<div class="uk-width-2-10">
{{$node->id}} - {{$node->desc}}
</div>
<div class="uk-width-2-10 testLoop">
<span>{{ $node->comment }}</span>
<a href="#edit-modal{{ $key }}" data-uk-modal><span class="uk-icon-check"></span></a>
</div>
</div>
</div>
<div id="edit-modal{{ $key }}" class="uk-modal">
<div class="uk-modal-dialog">
<div class="uk-width-1-1">
<div class="uk-grid uk-grid-small">
<div class="uk-width-2-10">
{{$node->id}} - {{$node->desc}}
</div>
<div class="uk-width-2-10 testLoop">
<span>{{ $node->comment }}</span>
</div>
</div>
</div>
</div>
</div>
@endforeach
function testLoop() {
var comment = document.getElementsByClassName('testLoop'),
commentText = comment;
for (var index = 0; index < commentText.length; index++) {
var element = commentText[index];
var getValue = element.children[0].innerHTML;
element.addEventListener('click',function(){
console.log('click');
})
}
}
testLoop();
解决方案
您的子字符串应该是(0,10)
十个字符。
let element = document.getElementById('text')
element.innerText = element.innerText.substring(0,10) + '***'
<span id='text'>Long long long long text</span>
另一种方法
而不是字符长度,使用max-width
,并将您的设置CSS
为截断并显示省略号。CSS 为您完成所有工作。
#text {
max-width: 90px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
<div id='text'>This is a long, long, long string.</div>
推荐阅读
- html - HTML/CSS Div 不会一直向下
- entity-framework - 按 LINQ 的顺序使用聚合函数
- angular - 共享服务不起作用,给出不同的行为
- r - 替换R中数据框中所有以n't结尾的单词
- android - 程序类型已存在:com.google.android.gms.common.api.zzd,, Message{kind=ERROR, text=程序类型已存在:
- mysql - 如何仅选择非空列?
- docker - 在 Docker Swarm 中安装 SSL 证书
- javascript - 使用 Vue 时出现“D3-tree”错误
- javascript - 当浏览器的某行出现错误时,有多少 JavaScript 会停止工作?
- node.js - 使用代理时出现 AssertionError