简体   繁体   中英

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:

$('#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}' .

Let's examine how the current template string will be expanded, if 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 .

As Andreas pointed out, a single quote in postDesc will cause problems. Here is a workaround for this: onclick="this.innerHTML = '${postDesc.replace(/([\\"\\'])/g,'\\$1')}' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM