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;
}
这将成功写入带有 linkl
类的 div。
我需要第一个 div 也包含类 linklactive
- 如果可能的话。
最佳答案
另一种方法是设置类,然后清除它:
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;
}
关于php - 为动态创建的 div 设置一个附加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41767553/