innerHTML example: With user input it doesn´t work, why?

帅比萌擦擦* 提交于 2019-12-13 05:32:28

问题


I have this working code, with an example of innerHTML:

<script type="text/javascript">
// ejemplo de innerHTML
function cambiarColor(){
    var oldHTML = document.getElementById('para').innerHTML;
    var newHTML = "<span style='color:lightgreen'>" + oldHTML + "</span>";
    document.getElementById('para').innerHTML = newHTML;
}
</script>
<p id='para'>Hola <b id='nombre'>gente</b> </p> 
<input type='button' onclick='cambiarColor()' value='Change Text'/>

But then I wanted to change color using some user input. My problem is that it doesn´t work. It shows (in the color the user chooses) the word "undefined". I´ve used the console and I understand that "mensaje" variable is not defined? Why is that?

<script type="text/javascript">
// ejemplo de innerHTML con User Input
function cambiarColorUser(){
    mensaje=document.getElementById('clase').value;
    nuevoColor=document.getElementById('nuevoColor').value;
    mensajeCambiado="<span style='color:"+ nuevoColor +";'>"+ mensaje +"</span>";
    document.getElementById('clase').innerHTML=mensajeCambiado;
}
</script>
<p id='clase'><h1>Mensaje que cambia de color</h1> </p>
<input type="text" id="nuevoColor">
<input type='button' onclick='cambiarColorUser()' value='Cambia el Color!'/>

UPDATE

After reading your replies, I´ve updated the code, that still won´t work (http://jsfiddle.net/vjze5/):

<script type="text/javascript">
// ejemplo de innerHTML con User Input
function cambiarColorUser(){
    var mensaje=document.getElementById('clase').innerHTML;
    var nuevoColor=document.getElementById('nuevoColor').value;
    var mensajeCambiado="<span style='color:"+ nuevoColor +";'>"+ mensaje +"</span>";
    document.getElementById('clase').innerHTML=mensajeCambiado;
}
</script>
<p id='clase'><h1>Mensaje que cambia de color</h1> </p>
<input type="text" id="nuevoColor">
<input type='button' onclick='cambiarColorUser()' value='Cambia el Color!'/>

Note: If I type "red" inside the text input, and open the console in Chrome, and type "cambiarColorUser()" it replies "undefined".


回答1:


In this line of your code:

mensaje=document.getElementById('clase').value;

.value is for some form controls, not for paragraph tags.

Perhaps you meant for that line of code to be:

mensaje=document.getElementById('clase').innerHTML;

Also, all local variables (variables intended to be used only within a funnction) should be declared with var in front of them. This isn't actually causing a problem in your current code, but is a very bad practice and will cause problems in the future.



来源:https://stackoverflow.com/questions/19610299/innerhtml-example-with-user-input-it-doesn%c2%b4t-work-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!