我正在尝试将这些变量添加到字符串段落中

时间:2018-10-26 03:48:43

标签: javascript html

我是Java脚本的相对论新手,并且我正在一个类中的项目上工作,这需要我们接受输入,将它们更改为变量,并在一个段落中实现它们。我们了解了我尝试过的称为模板文字的东西,但没有成功。我想知道是否有什么我想念的东西或另一种方式来做到这一点。

<button onclick="myFunction">Create my story!</button>
<script> 
    let name = document.getElementById("name") 
    let classAt = document.getElementById("class") 
    let prof = document.getElementById("prof") 
    let adject = document.getElementById("Adject") 
    let place = document.getElementById("place") 
    let length = document.getElementById("time") 
    let thing = document.getElementById("thing") 
    let person = document.getElementById("person") 
    let family = document.getElementById("fam") 

    function myFunction() {
        window.alert("Please Excuse ${name} from ${class} today.His 
        ${prof} says he is too ${Adject} to attend the ${place}. He 
        will return to school in ${time}. Please send their ${thing} 
        home with ${person}, his sister. signed, ${name}'s ${fam}") 
    }
</script>

1 个答案:

答案 0 :(得分:0)

用字符`包裹文本以在Javascript中创建模板文字。然后调用该函数。

function myFunction() {
    window.alert(`Please Excuse ${name} from ${class} today.His 
    ${prof} says he is too ${Adject} to attend the ${place}. He 
    will return to school in ${time}. Please send their ${thing} 
    home with ${person}, his sister. signed, ${name}'s ${fam}`) 
}

myFunction();

要从HTML元素获取文本内容,可以尝试以下操作:

const name = document.getElementById("name").textContent;

如果您不打算更改变量的值,请使用const代替let

希望能解决您的问题。