【问题标题】:calling a variable inside html在 html 中调用变量
【发布时间】:2009-11-12 21:47:10
【问题描述】:

我正在尝试制作一个脚本,当您输入十六进制值并按提交时,它会将文本颜色更改为输入的颜色。

看来问题是我在变量 new html 中调用变量“userInput”的方式

有什么想法吗?

<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'/>

【问题讨论】:

    标签: javascript html ajax variables getelementbyid


    【解决方案1】:

    我建议使用样式参考而不是添加越来越多的跨度:

    document.getElementById('para').style.color = userInput;
    

    【讨论】:

      【解决方案2】:

      这只是导致问题的一行:

      var newHTML = "<span style='color:" + userInput + "'>" + oldHTML + "</span>";
      

      【讨论】:

        【解决方案3】:

        您需要将 userInput 变量“注入”到您的 newHTML 变量中。见下文;

        <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'/>
        

        【讨论】:

        • 这行得通,但现在的问题是我没有正确考虑这一点,因为它只能更改一次,所以我必须重新开始
        猜你喜欢
        • 2022-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-25
        相关资源
        最近更新 更多