[英]Why am I getting : Uncaught SyntaxError: Unexpected token ILLEGAL here
[英]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>`;
}
但是當我點擊閱讀更多按鈕時:
Uncaught SyntaxError: unexpected token: identifierlocalhost:8000:1:22
我試圖刪除 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)
但問題是它沒有用完整的子字符串替換當前帖子描述,而是用列表中的最后一個帖子完整描述替換它!
將onclick="this.innerHTML = ${postDesc}
更改為onclick="this.innerHTML = '${postDesc}'
。
如果postDesc == "hello world"
,讓我們檢查當前模板字符串將如何擴展:
<p class="btn btn-link" onclick="this.innerHTML = hello world"> Read more</p>`;
. 當 JavaScript VM 嘗試執行this.innerHTML = hello world
,它會將hello
識別為未定義的標識符,這是可以容忍的,但隨后它遇到了另一個未定義的標識符world
,此時這是意外的,因此出現錯誤unexpected token: identifier
。
正如 Andreas 所指出的,postDesc 中的單引號會導致問題。 這是一個解決方法: onclick="this.innerHTML = '${postDesc.replace(/([\\"\\'])/g,'\\$1')}'
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.