I’m trying to build my own comment system.
Here’s the code that show a comment box when clicking on the “Reply” button:
function postComment(i, parentId) {
let content;
if (parentId === undefined) {
content = commentBox.value
} else {
content = eval("subCommentBox"+i).value
}
const body = JSON.stringify({
"post_slug": location.pathname.slice(1),
"username": "quantong",
"parent_id": parentId,
"content": content,
})
fetch("http://localhost:8080/comments", {
method: "post",
headers: { "Content-Type": "application/json" },
body: body
})
.then(resp => {
if (resp.status === 200) {
return resp.json()
} else {
console.log("Status: " + resp.status)
}
})
commentBox.value = "";
window.location.reload();
}
let allElements = document.body.getElementsByClassName("replybtn");
let addCommentField = function () {
for (let i = 0; i < allElements.length; i++) {
if (allElements[i] === this) {
if (document.getElementsByClassName("replyform")[i].innerHTML.length === 0) {
document.getElementsByClassName("replyform")[i].innerHTML = `
<div class="form-group">
<textarea class="form-control" id="subCommentBox`+i+`" rows="3"></textarea>
</div>
<div class="d-flex flex-row-reverse">
<button type="button" class="btn btn-success" onclick="postComment(` + i + `, ` + allElements[i].id + `)">Comment</button>
</div>
`
}
}
}
};
It worked fine if I put in a .js
file.
The thing is after use is logged in, I want to pass username and profile picture as a body to the backend side, so I moved it to App.svelte
file:
let commentBox;
function postComment(i, parentId) {
let content;
if (parentId === undefined) {
content = commentBox
} else {
content = eval("subCommentBox"+i).value
}
const body = JSON.stringify({
"post_slug": location.pathname.slice(1),
"image_url": responsePayload.picture,
"username": responsePayload.name,
"parent_id": parentId,
"content": content},
)
fetch("http://localhost:8090/comments", {
method: "post",
headers: { "Content-Type": "application/json" },
body: body
})
.then(resp => {
if (resp.status === 200) {
return resp.json()
} else {
console.log("Status: " + resp.status)
}
})
commentBox = "";
window.location.reload();
}
If I leave the innerHTML
text as it is, it caused:
Uncaught ReferenceError: postComment is not defined
If I change it from:
<button type="button" class="btn btn-success" onclick="postComment(` + i + `, ` + allElements[i].id + `)">Comment</button>
to:
<button type="button" class="btn btn-success" on:click={() => postComment(i, allElements[i].id)}>Comment</button>
it will be rendered as:
So, in a .svelte
file, how can I call a javascript function with parameters in innerHTML?