我想限制一段文字的大小。包装div具有动态创建的ID,并且段落文本也被动态插入。 HTML和JavaScript在同一文件中。

HTML

echo"
...
   <div id ='subTextWrapper$sub_id' >
      <p>$submission_text</p>
   </div>
...";


JavaScript:

echo"
<script>
...
var submissionId = $sub_id;

//Limit size of a submission if too long and show a link to read more
var submissionString = $('#subTextWrapper' + submissionId).html();

if (submissionString.split(' ').length > 50) {
   $('#subTextWrapper' + submissionId).html(submissionString.split(' ').slice(0, 50).join(' ')
   + ' ... '
   + `<a class='read-more' + submissionId>Read more</a>`);
}

$('a.read-more' + submissionId).click(function () {
    $('#subTextWrapper' + submissionId).html(submissionString);
});
...
</script>";



在上面的if语句中,我想将类名read-more与```变量submissionId连接起来:

`<a class='read-more' + submissionId>Read more</a>`


这似乎不起作用。我不是JS方面的专家,所以我们将不胜感激。请注意,当我删除变量submissionId时,它起作用了,但是显然,它扩展了我所有动态创建的提交。

最佳答案

concatenation似乎错了。

您当前正在插入的内容就是您看到的字符串:

<a class='read-more' + submissionId>Read more</a>


而不是submissionId的值。由于您没有正确处理两个不同的定界符。您有`整个a元素和'类。您要在添加submissionId之前关闭该类,而不是关闭主文字以自动包含submissionId的值


您可以像这样修复它(如果submissionId是字符串):

`<a class='read-more` + submissionId.trim() + `'>Read more</a>`


要么

`<a class='read-more@Sub.'>Read more</a>`.replace('@Sub.', submissionId.trim())


您也可以使用数组来构建字符串,以避免使用不同的分隔符:

//var submissionId = 1234;
var tString = [];
tString.push("<a class='read-more"); //REM: Open the class attribute and not closing it since submissionId  is part of the class
tString.push(submissionId); //REM: Adding the value of submissionId
tString.push("'>Read more</a>"); //REM: Closing the class attribute
console.log(tString.join('')); //-> <a class='read-more1234'>Read more</a>


由于submissionId在我看来像是一个ID /编号,请注意classnames shall not start with digits

此外,如果要限制字符串的字符,可以使用String.prototype.substring()代替:

submissionString.substring(0, 50);

10-05 19:41