用PHP变量更改元素颜色的Javascript

时间:2022-11-20 21:01:34

I am trying to write a Javascript function that changes the font color of an element. I was unsure how to fire off the function right away, so I called the javascript function with an onload call in the element tag. I am retrieving a value through PHP and loading it into the function: if value > 0, set font to green; else if value < 0, set font to red; else, set font to black. Here is what I have so far:

HTML header tag populated with the PHP value:
<h1 id="change" onload="checkChange()"><?php echo number_format(array_sum($total_balance), 2, '.', ''); ?></h1>

Javascript to change the font color:

我正在尝试编写一个更改元素字体颜色的Javascript函数。我不确定如何立即启动该功能,所以我在元素标签中调用了带有onload调用的javascript函数。我正在通过PHP检索一个值并将其加载到函数中:如果值> 0,则将字体设置为绿色;否则,如果值<0,则将字体设置为红色;否则,将字体设置为黑色。以下是我到目前为止:填充PHP值的HTML标头标记:

Javascript改变字体颜色:

 <script>
    function checkChange() {
        var change = <?php echo array_sum($total_balance); ?>;

        if change > 0 {
         document.getElementById("change").style.color = "#00FF00";
        } else if change < 0 {
             document.getElementById("change").style.color = "#FF0000";
        } else {
             document.getElementById("change").style.color = "#000000";
        }

    }
    </script>


With the code provided, the header shows the value, but the color is not affected. Thanks!

使用提供的代码,标题显示值,但颜色不受影响。谢谢!

1 个解决方案

#1


0  

onload is not valid for a h1 tag, put it on the body tag instead.

onload对于h1标签无效,请将其放在body标签上。

http://www.w3schools.com/jsref/event_onload.asp

or you can run it before onload with an inline script after the h1 tag.

或者您可以在使用h1标记之后的内联脚本进行onload之前运行它。

or you could set it server side and have no JavaScript.

或者您可以将其设置为服务器端并且没有JavaScript。

If you are working on JavaScript be sure your browsers debugger is set to pause on exceptions.

如果您正在使用JavaScript,请确保您的浏览器调试器设置为暂停异常。

#1


0  

onload is not valid for a h1 tag, put it on the body tag instead.

onload对于h1标签无效,请将其放在body标签上。

http://www.w3schools.com/jsref/event_onload.asp

or you can run it before onload with an inline script after the h1 tag.

或者您可以在使用h1标记之后的内联脚本进行onload之前运行它。

or you could set it server side and have no JavaScript.

或者您可以将其设置为服务器端并且没有JavaScript。

If you are working on JavaScript be sure your browsers debugger is set to pause on exceptions.

如果您正在使用JavaScript,请确保您的浏览器调试器设置为暂停异常。