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

时间:2017-01-20 15:50:35

标签: php html

shopt -s expand_aliases

这会成功写入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; } 类的div。

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

2 个答案:

答案 0 :(得分: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;    
}

答案 1 :(得分:4)

您可以计算您循环的次数,在第一次运行中,您添加该类...

function givemetitles($table,$row_active = 0){

    global $db;
    $titles = '';
    $stmt = $db->query("SELECT id, title FROM " . $table . " ORDER BY title ASC");
    $count = 0;
    while($row = $stmt->fetch()){
        if($count == $row_active){
            $titles.="<div data-id=" . $row['id'] . " class='linkl linklactive'>" . $row['title'] . "</div>\n";
        }else{
            $titles.="<div data-id=" . $row['id'] . " class='linkl'>" . $row['title'] . "</div>\n";
        } 
        $count++;
    }
    echo $titles;

}

漂亮?不,不是,但它确实起作用。

也就是说,在这种情况下,cale_b answer更重要,&#34;更漂亮&#34; 。我保留这个答案,因为你可以定义哪一行获得类。