简体   繁体   English

如何将函数的值放入模板文字中?

[英]How to put the value of a function inside the template literal?

Im making a comment system and is required to put the stars inside of template literal with the purpose that the number of stars stay next to the name of the person.我正在制作一个评论系统,并且需要将星星放在模板文字中,目的是将星星的数量留在人名旁边。 Until now the value is showing me "undefined" screenshoot screenshot comment system到目前为止,该值向我显示“未定义”截屏截图评论系统

this is the javascript code这是javascript代码

const txtNombre = document.getElementById("text-nombre");
const txtParrafo = document.getElementById("text-area");
const boton = document.getElementById("btnAgregar");
const listado = document.getElementById("contenedor-filas");
const radio = document.getElementsByName("rate");

boton.addEventListener("click", agregarALista);

function agregarALista() {
    let nombre = txtNombre.value;
    var valor = txtParrafo.value;

    const elHtml = document.createElement("div");

    elHtml.innerHTML = `
    <div class="row" id="fila-segunda">
        <div class = "col-6">
            ${nombre}
        </div>

        <div class = "col-6">
            ${estrellitas()}
        </div>
    </div>

    <div class="row" id="fila-tercera">
        <div class = "col">
            ${valor}
        </div>
    </div>
    `;
    listado.appendChild(elHtml);

    txtNombre.value = "";
    txtParrafo.value = "";
}




let estrellitas = function() {
    radio.forEach(function(elementos) {
        if (elementos.checked) {
            estrellas = document.createElement("h3");
            estrellas.setAttribute("class", "stars");
            let s = "";
            for (i = 0; i < elementos.value; i++) {
                s += "★";
            }
            estrellas.textContent = s;
            listado.appendChild(estrellas);
        }
    });
}

Your function estrellitas() is missing a return statement and will therefore return undefined .您的函数estrellitas()缺少 return 语句,因此将返回undefined Otherwise, your syntax for including function return values in string template literals is correct:否则,在字符串模板文字中包含函数返回值的语法是正确的:

 let x = (a, b) => a > b; let a = 10, b = 20; console.log(`${a} is greater than ${b}? ${x(a, b)}`);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM