在echo语句中串联javascript字符串和变量

时间:2019-07-02 06:55:35

标签: javascript php jquery

我想限制一段文字的大小。包装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时,它可以工作,但显然它会扩展我所有动态创建的提交。

2 个答案:

答案 0 :(得分:0)

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);

答案 1 :(得分:0)

那样行不通吗?

echo"
<script>
//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'$sub_id).click(function () {
$('#subTextWrapper'$sub_id).html(submissionString);
});
...
</script>";

或者您也可以这样连接

 $('a.read-more'".$sub_id.")