为动态创建的div设置一个额外的类

qad*_*nza 2 html php

function givemetitles($table){
    global $db;
    $titles = '';
    $stmt = $db->query("SELECT id, title FROM " . $table . " ORDER BY title ASC");
    while($row = $stmt->fetch()){
        $titles.= 
                  "<div data-id=" . $row['id'] . 
                  " class='linkl'>" . $row['title'] . "</div>\n"; 
     }
     echo $titles;
}
Run Code Online (Sandbox Code Playgroud)

这会linkl成功地为类写入div .

我需要第一个div也包含类linklactive- 如果可能的话.

ran*_*ame 6

另一种方法是设置类,然后清除它:

function givemetitles($table){
    global $db;
    $titles = '';
    // set $first_class to the class you want for the first record
    $first_class = ' linklactive';
    $stmt = $db->query("SELECT id, title FROM " . $table . " ORDER BY title ASC");
    while( $row = $stmt->fetch() ) { 
        // include $first_class in the $title value
        // tweaked to use string interpolation
        // Switched to PHP_EOL instead of \n
        $titles.= "<div data-id='{$row['id']}' class='linkl{$first_class}'>{$row['title']}</div>" . PHP_EOL;
        // reset $first_class to be empty string
        $first_class = ''; 
    }

    echo $titles;    
}
Run Code Online (Sandbox Code Playgroud)