我们开发的代码使得文本在 200 个字符后应该被 chop ,但是当在文本之间添加超链接时它没有按预期工作。在这种情况下,文本甚至会在 200 个字符之前被 chop 。
我附上了两个屏幕截图,1. 文本被正确 chop 和 2. 添加了超链接 where文本未正确 chop 。
请让我知道在添加超链接时如何使文本在 200 个字符后正确 chop 。
任何帮助将不胜感激!!
enter image description here ur.com/7XSjr.png
enter code here
Java script :
var MAX_CHARS = 200;
var ELLIP = String.fromCharCode(8230);
function truncateIdeaText (str) {
if (str.length < MAX_CHARS) return str;
return str.substr(0, MAX_CHARS) + ' ' + ELLIP;
}
var tagIdx = 0;
/* Creates a single block (closeup)*/
function createCloseup (idea, pageNr) {
var d = jQuery('<div>', {'class': 'ideasblock'});
// the bellow replace of /ideas/ to /Ideas/ id to get arround the ideas rewrite file
d.append("<a class='ideas-link' href='"+browserUrl+"/"+idea.roomId+"/"+"'><img src='" + idea.image + "' width='512' data-page-nr='" + pageNr + "' onclick=javascript:fnSubmit('"+idea.roomId+"'); />" +
"<h2 class='ideasHeadLine'>" + idea.headLine + "</h2>" +
"<div class='ideasdate'>" + idea.startDate + "</div>" +
"<p class='ideasPara'>" + truncateIdeaText(idea.text) + "</p>");
CSS :
a.ideas-link {
color: inherit !important;
text-decoration: none !important;
}
a.ideas-link:hover .ideasHeadLine {
text-decoration: underline;
}
.ideasPara{
margin-top: 10px;
margin-bottom: 0px;
text-align: left;
left: 0px;
width: 512px;
display:block;
font-family: 'Verdana';
font-weight: 400;
font-style: normal;
font-size: 12px;
color: #333333;
line-height: 18px;
}
最佳答案
在我看来,最简单的解决方案(代码更改最少)可能是这样的 -
定义更多变量(即 linkTagBaseLength、linkHrefLength 等)
然后使用 bool 变量来确定链接是否存在。
在函数 truncateIdeaText()
中将此代码与 MAX_CHARS
一起使用。
然而不清楚您是否希望在屏幕上将链接显示为代码(请参阅我上面的解决方案)。
另一方面,如果您希望将链接添加到 span 作为 html 元素
我建议你先创建你需要的元素(在局部变量中定义它们以便更好地控制程序)然后使用 jquery 的 append
功能。
(代码示例为 see this question)。
或者您始终可以使用 Javascript 的 Document.createElement()
功能。
关于javascript - 在 html 中添加超链接时,文本未正确 chop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34760100/