【发布时间】:2023-03-16 12:58:01
【问题描述】:
我想在我的网站上创建一个搜索器,问题是当我显示我的数据库的结果时,有些描述非常大,我试图截断描述以使其更直观。
我想要做的是显示应该是这样的描述:
blablabla 描述 bla bla bla 更多描述
进入这个:
blablabla 描述 bla bla bla mo...
我想显示的最大长度是 340 个字符,我想到的代码就是这个
...
var newText = document.createElement("p"); //i create a new element of text
var newContent = document.createTextNode(projects.description); //i set the text to
//be the description from the database [the type of this var is Text]
if(newContent.length > 340) { //if the description is bigger than 340
var result=newContent + ""; //i convert the newContent type to string since
//substring only works with strings and not Text
result=result.substring(0, 337)+"..."; //i trunc the description
newContent=result; // <-- here i need to assign the result[string] to newContent[Text]
}
newText.appendChild(newContent);
...
希望您能告诉我如何将字符串再次转换为文本或以其他方式截断描述。
谢谢,伯特兰
【问题讨论】:
-
看起来您已经在
projects.description中获得了一个字符串值——因此请根据您的需要对其进行修改,然后之后从中创建一个文本节点。 -
为什么不试试
if (projects.description.length > 340)....?然后对文本做任何你想做的事情,最后把它放到 p 元素中
标签: javascript string text types