【发布时间】: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">- 这里缺少什么?您必须将${postDesc}括在引号中,或者最好不要为此使用内联 JS (->.addEventListener())
标签: javascript json django ajax