[英]Why am i getting Uncaught SyntaxError: unexpected token: identifier
for (post of posts) { //Posts are returned from a python django function
let readMore = '';
let postDesc = post.fields.description
if (post.fields.description.length > 227) {
readMore = `<p class="btn btn-link" onclick="this.innerHTML = ${postDesc}"> Read more</p>`;
};
output += `<p class="card-text" style="white-space: pre-line;">${post.fields.description.substring(0, 227)} ${readMore}</p>`;
}
But when I click the read more button:但是当我点击阅读更多按钮时:
Uncaught SyntaxError: unexpected token: identifierlocalhost:8000:1:22
I tried to remove the onclick and replace it with this at the end:我试图删除 onclick 并在最后用它替换它:
$('#mainPosts').append(output)
function showMore() {
$('.readMore').click(function(e) {
e.preventDefault();
$(this).parent().html(`<br> ${post.fields.description}`)
})
}
let g = document.createElement('script');
let s = document.getElementsByTagName('script')[0]
g.text = showMore();
s.parentNode.insertBefore(g, s)
But the problem is it's not replacing the substring current post description with the full one, it's replacing it with the very last post full description in the list!但问题是它没有用完整的子字符串替换当前帖子描述,而是用列表中的最后一个帖子完整描述替换它!
Change onclick="this.innerHTML = ${postDesc}
to onclick="this.innerHTML = '${postDesc}'
.将
onclick="this.innerHTML = ${postDesc}
更改为onclick="this.innerHTML = '${postDesc}'
。
Let's examine how the current template string will be expanded, if postDesc == "hello world"
:如果
postDesc == "hello world"
,让我们检查当前模板字符串将如何扩展:
<p class="btn btn-link" onclick="this.innerHTML = hello world"> Read more</p>`;
. . When the JavaScript VM tries to execute
this.innerHTML = hello world
, it recognizes hello
as an undefined identifier, which will be tolerated, but then it encounters world
, another undefined identifier, which is unexpected at this point, hence the error unexpected token: identifier
.当 JavaScript VM 尝试执行
this.innerHTML = hello world
,它会将hello
识别为未定义的标识符,这是可以容忍的,但随后它遇到了另一个未定义的标识符world
,此时这是意外的,因此出现错误unexpected token: identifier
。
As Andreas pointed out, a single quote in postDesc will cause problems.正如 Andreas 所指出的,postDesc 中的单引号会导致问题。 Here is a workaround for this:
onclick="this.innerHTML = '${postDesc.replace(/([\\"\\'])/g,'\\$1')}'
.这是一个解决方法:
onclick="this.innerHTML = '${postDesc.replace(/([\\"\\'])/g,'\\$1')}'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.