calling a variable inside html
I am trying to make a script that when you type in a hex value and press submit itchanges the text color to the color inputted.
It seems the problem is the way i am calli开发者_StackOverflow中文版ng the variable "userInput" inside the variable new html
Any Ideas?
<script type="text/javascript">
function changeText3(){
var userInput = document.getElementById('userInput').value;
var oldHTML = document.getElementById('para').innerHTML;
var newHTML = "<span style='color:userInput'>" + oldHTML + "</span>";
document.getElementById('para').innerHTML = newHTML;
}
</script>
<p id='para'>Welcome to the site <b>dude</b> </p>
<input type='text' id='userInput' value='#' />
<input type='button' onclick='changeText3()' value='Change Text'/>
I would suggest to use the style reference instead of adding more and more spans:
document.getElementById('para').style.color = userInput;
It's just the one line that's causing the problem:
var newHTML = "<span style='color:" + userInput + "'>" + oldHTML + "</span>";
you need to "inject" the userInput variable into your newHTML variable. See below;
<script type="text/javascript">
function changeText3(){
var userInput = document.getElementById('userInput').value;
var oldHTML = document.getElementById('para').innerHTML;
var newHTML = "<span style='color:" + userInput + "'>" + oldHTML + "</span>";
document.getElementById('para').innerHTML = newHTML;
}
</script>
<p id='para'>Welcome to the site <b>dude</b> </p>
<input type='text' id='userInput' value='#' />
<input type='button' onclick='changeText3()' value='Change Text'/>
精彩评论