问题
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