any time a negative number on site, color it red

时间:2017-06-19 14:07:26

标签: javascript colors

Thinking there's probably some javascript out there that achieves this, but everything I've found thus far seems to be very conditional. I'm trying to figure out something across my entire site that anytime there's a negative number like -30, it's always displayed in red. These values will be scraped data outputs via php. So anytime on my html page, if there's a displayed text value that's a negative, it's turned red, that's what I'm trying to do.

Not sure if this is enough details, but basically that php is outputting data like: -30%. I have a xhtml file referencing many php files scraping and outputting values and numbers. I'm trying to find a way to put some script into my xhtml file that says: if value on this page ANYWHERE is less than 0, color red. Etc

Anyone know of some good examples of this?

My test coding is this:

xml:

<p><font color="grey">All time high</font></p>
<?php include 'ref3.php';?>
<?php include 'alltimenasfullnumber.php';?>

  <p><font color="grey">Yearly growth</font></p>
   <?php include 'nasyearlygrowth.php';?>

php ref:

<?php 

 $doc = new DOMDocument;

// foriegn stocks
 $doc->preserveWhiteSpace = false;


 $doc->strictErrorChecking = false;
  $doc->recover = true;

 $doc->loadHTMLFile('http://www.money.cnn.com/data/markets/');

 $xpath = new DOMXPath($doc);

  $query = "//a[@class='world-market']";

  $entries = $xpath->query($query);
 foreach ($entries as $entry) {
 echo trim($entry->textContent);  // use `trim` to eliminate spaces
 }

 ?>

1 个答案:

答案 0 :(得分:2)

我认为最好的解决方案是将xhtml页面上的每个结果打包成一个独特的标记(在我的示例中为pre)。 这里有我的代码,希望这会对你有所帮助:

<html>
<head>
    <style type="text/css">
        .redFont {
            color: red;
        }
    </style>
    <script type="text/javascript">
        function redText() {
            var elements = document.getElementsByTagName('pre')
            for(i=0; i< elements.length; i++)
            {
                if(elements[i].innerHTML < 0) {
                   elements[i].classList.add('redFont');
                };
            }
        }

    </script>
</head>
<body>
    <p>
      <font color="grey">Yearly growth</font>
    </p>
    <pre><?php echo 30; ?></pre>
    <pre><?php echo -12; ?></pre>
    <pre><?php echo 15; ?></pre>
    <script>redText();</script>
</body>

再见 劳拉