简体   繁体   English

使用JavaScript附加HTML输入会产生“未定义”的值

[英]Appending HTML inputs using JavaScript gives “undefined” value

I have a small code trying to append values using HTML inputs to the same document. 我有一个小代码试图将使用HTML输入的值附加到同一文档中。

 <h2 id="myh"> Header</h2> <input type="text" id="text"> <button onclick="func()">Append</button> <script type="text/javascript"> var child = document.getElementById("text").value; function func() { var h = document.getElementById('myh'); h.insertAdjacentHTML('afterend', '<p> New Para' + toString(child) + '</p>'); } </script> 

the variable child dose not take the text value from the input, which outputted as `undefined' 可变child不会从输入中获取文本值,该文本值输出为“未定义”

image 1: typed Test 图片1:输入Test

在此处输入图片说明

Image 2: Clicked the Button 图2:单击按钮

在此处输入图片说明

how to get the value form the input as New ParaTest? 如何从输入中获取值作为New ParaTest?

Code Edited using the answer. 使用答案编辑代码。

Your variable should be global. 您的变量应为全局变量。 Try taking it inside the function and then check it. 尝试将其放入函数中,然后进行检查。

    function func(){
        var child = document.getElementById("text").value;
        var h = document.getElementById('myh');
        h.insertAdjacentHTML('afterend','<p> New Para' + toString(child) + '</p>');
    }

You don't need toString() method, remove it. 您不需要toString()方法,将其删除。

Get the reference of element in the child variable and get the value the func() 获取child变量中元素的引用,并获取value func()

 var child = document.getElementById("text"); function func() { var h = document.getElementById('myh'); h.insertAdjacentHTML('afterend', '<p> New Para: ' + child.value + '</p>'); } 
 <h2 id="myh"> Header</h2> <input type="text" id="text"> <button onclick="func()">Append</button> 

child variable needs to assign inside func function and don't need toString() try this child变量需要在func函数内部分配,并且不需要toString()尝试一下

 function func(){ var h = document.getElementById('myh'); let child = document.getElementById("text").value; h.insertAdjacentHTML('afterend','<p> New Para' + child + '</p>'); } 
 <html> <body> <h2 id="myh"> Header</h2> <input type="text" id="text"> <button onclick="func()">Append</button> </body> </html> 

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

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