首页 > 解决方案 > 在循环中截断文本的字符

问题描述

我这里有点问题。

我基本上是在 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();

标签: javascripthtml

解决方案


您的子字符串应该是(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>


推荐阅读