php - 为动态创建的 div 设置一个附加类

标签 php html

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/

相关文章:

javascript - 使用自定义超链接包装 Instagram 嵌入

html - 不要在 Placeholder IE10 上应用文本转换

php - 通过 <a href> 使用 mysql 主机在 PHP 中打开新页面

javascript - 如何在渲染 ejs View Node.js 时捕获错误

html - 如何检测网页拦截器并对其采取行动?

javascript - 用javascript显示奇数

php - Zend\Db\ResultSet\ResultSet 对象在哪里存储检索到的数据?

javascript - 使用 javascript 从共享 iCloud 获取数据

php - 如何最好地将 mysql 数据实现到一行 javascript 代码中?

php - 如何附加 MYSQL JSON