ProgLang:HTML中的Javascript

问题:我正在通过注释框(其名称)获得用户输入,并希望在整个其余代码中将其插入字符串中间。例如:“您还好吧,名字,我很担心!”

我尝试使用${firstname},但是它没有在结果注释框中显示字符串的其余部分。

    Enter Your First Name
<br><input type="text" id=firstname name="firstname" onblur="addNameToCommentBox(this)"><br><br>
.
Opening Sentence <br>
    <input type="checkbox" onclick="addToCommentBox(this);" name="grade" value="statement1. statement1. " + ${firstname}.`+ "statement1. statement1.">Statement1. indentifier user read on page<br>

    Second Sentence <br>
    <input type="checkbox" onclick="addToCommentBox(this);" name="grade" value="statement2. statement2.  ">Statement2. indentifier user read on page<br>
    <br>
...
Resulting Block<br>
    <textarea id="comment" rows="10" cols="80"></textarea><br>
</form>
<script>
function addNameToCommentBox(nameElement) {
    var comment = $("#comment");
        comment.val(comment.val() + " " + nameElement.value); }

function addToCommentBox(checkboxElement) {
    var comment = $("#comment");
    if (checkboxElement.checked === true) {
        comment.val(comment.val() + " " + checkboxElement.value);
    } else {
        var currentComment = comment.val();
        currentComment = currentComment.replace(checkboxElement.value, "");
        comment.val(currentComment);


你能告诉我吗?

最佳答案

您可以将模板设置为"statement1.statement1 {0} statement1. statement1."

然后编写一个函数以通过传递参数来获取消息。

function getComment(template, args){
return args.reduce((acc, element) => {
    console.log(element);
    acc = acc.replace(/{\d}/, element);
    return acc;
}, template);}


Codepen链接:https://codepen.io/nithinthampi/pen/gOYJopP

07-24 17:24