开发者

How to: Conditionally format a <td>, that is generated via MySQL query, based on content and using PHP/JavaScript

开发者 https://www.devze.com 2023-03-21 16:50 出处:网络
I have a database table that contains: Industry risk -------------- A B C And so on. I use query.php to generate a dynamic table to index.php and refresh it automatically using AJAX. The data is pu

I have a database table that contains:

Industry risk
--------------
      A
      B
      C

And so on. I use query.php to generate a dynamic table to index.php and refresh it automatically using AJAX. The data is pulled with:

$sql="SELECT * FROM scoreboard";

And the table generated with:

// Construct the table

echo "<table id='querytable'>\n";

The result is processed by query.js and displayed in index.php with: <div id="querydiv"></div>. So far, so good. Now for the tricky part. I want to conditionally format the background of the <td> based on the content, so that if it contains "A" then background-color:red;. The <td> are generated like so:

// Construct the array

while($row = mysql_fetch_assoc($result)){
    echo '<tr>'."\n";
    echo "<td align='center'>{$row['codcliente']}</td>\n" . "<td align='center'>{$row['nombre']}</td>\n" . "<td align='center'>{$row['ejecutivo']}</td>\n" . "<td align='center'>{$row['banca_as400']}</td>\n" . "<td align='center'>{$row['banca_real']}</td>\n" . "<td align='right'>$&nbsp;".number_format($row['ingresos'], 2)."</td>\n" . "<td align='center'>{$row['ciiu']}</td>\n" . "<td align='center'>{$row['division']}</td>\n" . "<td align='center'>{$row['actividad']}</td>\n" . "<td align='center'>{$row['riesgo_industria']}</td>\n" . "<td align='center'>{$row['riesgo_cliente']}</td>\n" . "<td align='center'>{$row['fecha']}</td>\n" . "<td align='center'>{$row['analista']}</td>\n";
    echo '</tr>'."\n";
}
echo "</table>\n";

I made a JavaScript file called highlight.js which contains:

$(function() {
            $("#querytable td:contains('A')").css('background-color','#C0504D'),
            $("#querytable td:contains('B')").css('background-color','#FDE480'),
            $("#querytable td:contains('C')").css('background-color','#9BBB59');
            });

And I try to call it f开发者_JAVA技巧rom query.php using:

// Load higlighting syntax

echo "<script type='text/javascript' src='highlight.js'></script>";

but nothing happens. I've tried giving the <div> tag and id and calling the JavaScript from index.php (since it has HTML and a <head> tag), but that didn't work either.

Is there anyway to do this? What am I doing wrong? Thanks!

Additional info. Contents of query.js:

// Customize these settings

var seconds = 2;
var divid = "querydiv";
var url = "query.php";

// Refreshing the DIV

function refreshdiv(){

// The XMLHttpRequest object

var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support AJAX.");
return false;
}
}
}

// Timestamp for preventing IE caching the GET request

fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}

var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;

// The code...

xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout('refreshdiv()',seconds*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}

// Start the refreshing process

var seconds;
window.onload = function startrefresh(){
setTimeout('refreshdiv()',seconds*1000);
}


Why don't you just use css?

Add the value to the class attribute on the td then set the rules in css.

Add the class like class='CONTENTS':

echo "<td align='center' class='{$row['codcliente']}'> ...

And then replace your jQuery code with a stylesheet:

#querytable td.A {background-color : #C0504D; }
#querytable td.B {background-color : #FDE480; }
#querytable td.C {background-color : #9BBB59; }

In your example the content was simple and valid css, if the contents had spaces or started with numbers you would need to transform them to valid css class names.

(edit, I copied the js code into my css without fixing the syntax)


The problem is that highlight.js runs too early. It runs immediately, dutifully looking for all matching elements and coloring them, but, alas, the asynchronous query hasn't yet inserted the content to be matched.

It may appear to be instantaneous, but in fact (I believe) you have an order of operations problem.

So to solve it, you need to run the coloring code after the queried content has been injected into the page. This would happen as part of the $.ajax or $.load call (not specified in the problem description) that you use to bring in the query.php content.

Hope this helps!


jimbojw explained to you why your code isn't working, you need to call the code in highlight.js after you update your table. He thought you were using jQuery for the AJAX part, but you aren't. So you have two options, change your code to use jQuery AJAX functions or call your highlight code from inside xmlHttp.onreadystatechange

xmlHttp.onreadystatechange=function(){
    if(xmlHttp.readyState==4){
        document.getElementById(divid).innerHTML=xmlHttp.responseText;
        setTimeout('refreshdiv()',seconds*1000);

        // call the code after updating the DOM tree
        $("#querytable td:contains('A')").css('background-color','#C0504D'),
        $("#querytable td:contains('B')").css('background-color','#FDE480'),
        $("#querytable td:contains('C')").css('background-color','#9BBB59');
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消