【问题标题】:Why am i getting Uncaught SyntaxError: unexpected token: identifier为什么我会收到 Uncaught SyntaxError: unexpected token: identifier
【发布时间】:2020-12-27 13:16:48
【问题描述】:
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 = I'm a description"&gt; - 这里缺少什么?您必须将 ${postDesc} 括在引号中,或者最好不要为此使用内联 JS (-> .addEventListener())

标签: javascript json django ajax


【解决方案1】:

onclick="this.innerHTML = ${postDesc} 更改为onclick="this.innerHTML = '${postDesc}'

让我们看看当前模板字符串是如何展开的,如果postDesc == "hello world":

&lt;p class="btn btn-link" onclick="this.innerHTML = hello world"&gt; Read more&lt;/p&gt;`;。当 JavaScript VM 尝试执行 this.innerHTML = hello world 时,它会将 hello 识别为未定义的标识符,这是可以容忍的,但随后会遇到另一个未定义的标识符 world,此时这是意外的,因此出现错误 @987654328 @。

正如 Andreas 指出的,postDesc 中的单引号会导致问题。这是解决此问题的方法:onclick="this.innerHTML = '${postDesc.replace(/([\"\'])/g,'\$1')}'

【讨论】:

  • 这只有在postDesc 中没有单引号时才有效 -> 不要使用内联 JS
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-29
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多