在下面的代码中,我试图 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。为了安全起见,将代码放在带有 setTimeout
的 window.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 来更改它
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/