javascript - chop <a> 标签文本

标签 javascript html

在下面的代码中,我试图 chop <a>标签文本:

<a href='test'>
    <script>
        truncate("truncate this text");
    </script>
</a>

function truncate(string){
    if (string.length > 5)
        return string.substring(0,5)+'...';
    else
        return string;
};

https://jsfiddle.net/fcq6o4Lz/6/

但返回 error Uncaught ReferenceError: truncate is not defined

如何从 <a> 中调用此函数标签?

最佳答案

为什么

出现错误的原因是您的计算机尚未运行定义truncate 的代码。该函数在页面完成加载之前运行,其中包括 JavaScript。为了安全起见,将代码放在带有 setTimeoutwindow.onload 中。

window.onload = function(){setTimeout(function () {
    truncate("truncate this text");
},1);};

如何

此外,与 PHP 等语言不同。 return 不会放置任何文本。做这样的事情:

<a id="result-location" href='test'>
        <script>
        window.onload = function(){setTimeout(function () {

            document.getElementById('result-location').innerHTML = truncate("truncate this text");

        },1);};
        </script>
</a>

Fiddle


JSFiddle 修复

请记住将函数保留在 window.onload 之外。您可以在 JSFiddle 中通过将其设置为 no-wrap 来更改它

Choose No-wrap


CSS

您可以使用 CSS 来 chop 文本

.truncate {
    width: 50px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: inline-block;
}

这将导致文本在 50px 之后被 chop ;

.truncate {
  width: 50px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
}
<a class="truncate">This text is truncated</a>

关于javascript - chop <a> 标签文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29870612/

相关文章:

html - 使图像在其他图像下方对齐

javascript - 将绑定(bind)传递给 Angular 组件中的 TemplateUrl

javascript - 使用 highcharts.js 改变背景颜色

javascript - Jquery 自动完成功能无法正常工作

javascript - 如何破坏内容安全策略?

html - 如何在 slider 中居中对象

javascript - ES6 : How to store the object inside this class?

javascript - React - 双花括号与一个大括号之间的区别枚举属性

Javascript:从父( super ?)函数调用子函数。

html - 调整 TextAreaFor 的宽度