【问题标题】:Convert type string to type Text on Javascript在 Javascript 上将类型字符串转换为文本类型
【发布时间】: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 &gt; 340) ....?然后对文本做任何你想做的事情,最后把它放到 p 元素中

标签: javascript string text types


【解决方案1】:

您的问题是您正在将一个字符串引用而不是一个文本节点的引用传递给您创建的段落元素的appendChild 方法。

var newContent = document.createTextNode(projects.description);

在这一行,您创建一个文本节点,并将对该文本节点的引用放入变量newContent

newContent = result;

在这一行中,您将变量 newContent 的值替换为对您创建的字符串的引用。

解决方案

您有很多解决方案的选择,但这里有两个显而易见的选择。

一种解决方案是访问文本节点的nodeValue 属性以设置其内容:

var newContent = document.createTextNode(projects.description);

if (newContent.nodeValue.length > 340)
    newContent.nodeValue = newContent.nodeValue.substring(0, 337) + '...';

另一种选择是第一次将createTextNode 参数传递给正确的字符串。三元运算符在这里可以很好地工作:

var newContent = document.createTextNode(
        projects.description.length > 340
        ? projects.description.substring(0, 337) + '...'
        : projects.description);

现在,当您将 newContent 附加到段落元素 newText 时,它将传递对文本节点的引用,而不是字符串。

newText.appendChild(newContent);

这是demonstration


注意,用户@epascarello 评论说存在一个 CSS 规则,可以自动将省略号添加到文本中,而无需使用 JavaScript。这是link to an explanation of the rule。请注意,这是一条 CSS3 规则。


这是另一个处理此问题前提的 StackOverflow Q&A。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-22
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 2010-09-20
    相关资源
    最近更新 更多