問題

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

  相同標籤的其他問題

javascripthtmlstringuser-input