我想将变量插入到类似html文本的代码段中
<form action="#" method="post">
<textarea class="form-control" name="comment" id="editComment25"></textarea >
<br>
<button class="btn btn-primary" id="commentBtnID25">Save Edits</button >
<a href="#">cancel</a>
</form >
我尝试了一种笨拙的解决方案:
var comment_id = $(e.target).attr("id")
var editCommentID = "editComment" + comment_id
var commentBtnID = "commentBtnID" + comment_id
var commentEditForm = '<form action = "#" method = "post"><textarea class="form-control" name ="comment" '
commentEditForm += 'id="' + editCommentID + '"></textarea > <br>';
commentEditForm += '<button class="btn btn-primary" id="' + commentBtnID + '">Save Edits</button > <a href="#">cancel</a></form >'
像python一样在这里可以插值吗?
commentEditForm = """"
<form action="#" method="post">
<textarea class="form-control" name="comment" id="%s"></textarea >
<br>
<button class="btn btn-primary" id="%s">Save Edits</button >
<a href="#">cancel</a>
</form >
""" %(editCommentID, commentBtnID)
答案 0 :(得分:3)
使用模板文字立即定义所需的字符串可能会更容易:
var comment_id = '25'; // $(e.target).attr("id")
var commentEditForm = `
<form action="#" method="post">
<textarea class="form-control" name="comment" id="editComment${comment_id}"></textarea >
<br>
<button class="btn btn-primary" id="commentBtnID${comment_id}">Save Edits</button >
<a href="#">cancel</a>
</form >
`;
console.log(commentEditForm);