简体   繁体   中英

Putting dynamically created ID into javascript

So I have a script that auto-generates ID's based on a column in a database. like such:

echo "<tr class='task' id='task-" . $row['task_id'] . "'>";

And then I have a script that is below that I am wanting it to change each tr class name based on some information from another column. I tried placing the same code 'task-". $row[task_id] ."' into the document.getElementById field but it didn't resolve in the browser. resolve meaning it stayed as 'task-" . $row[task_id] . "' instead of changing $row[task_id] into a number. I need to make that change to a number so it matches the id's of the tr .

var resolved = <?php echo $_SESSION['resolved']; ?>;
    if (resolved == 1) 
    {
        document.getElementById('task-" . $row[task_id] . "').className ="task resolved";
    }
    else
    {
        document.getElementById('task-" . $row[task_id] . "').className =" task";
    }

You need to echo out the variables like so:

var resolved = <?php echo $_SESSION['resolved']; ?>;

if (resolved == 1) 
{
    document.getElementById('task-<?php echo $row['task_id'] ?>').className ="task resolved";
}
else
{
    document.getElementById('task-<?php echo $row['task_id'] ?>').className =" task";
}

But it's better to not do it in javascript but to just do it in your PHP like so:

echo "<tr class='task " . ($_SESSION['resolved'] == 1 ? 'resolved' : '') ."' id='task-" . $row['task_id'] . "'>";

that adds the resolved class to as you are generating your HTML. However you will probably need a better way to test if a task is resolved because with the $_SESSION['resolved'] == 1 it's going to mark ALL tasks as resolved. So assuming your row has a column like `$row['resolved'] you could do:

echo "<tr class='task " . ($row['resolved'] == 1 ? 'resolved' : '') . "' id='task-$row[task_id]'>";

No need for javascript, if your status is in a column of that table....

if($row['resolved']=="1){
    $class="task resolved";
} else {$class = "task";}

echo "<tr class='".$class."' id='task-" . $row['task_id'] . "'>";

Or a much simpler version...

echo "<tr class='task ".($row['resolved'] == 1 ? 'resolved' : '')."' id='task-".$row['task_id']."'>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM