簡體   English   中英

如何在html選項標簽中使用php條件

[英]how to use php condition in html option tag

我有這個功能,當 $selected 等於 $row['id'] 時,我想在“option”標簽中使用“selected”屬性。 請注意它不是 php 代碼之間的常見 html 標簽,注意 html 選項標簽每次在 while 循環中都添加到 $output 變量中。

public function getCategoriesList(&$output = '',
                                      $parent = 0, $seprator = '', $selected=1)
    {
        $sql = "SELECT * FROM categories WHERE `parent_id` = $parent ";
        $stmt = $this->pdoConnection->prepare($sql);
        $stmt->execute();
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            $output .= "<option value=".$row['id']." ($row[id]==$selected)? selected :''>
                            ".$seprator.$row['title']."
                        </option>";


          $this->getCategoriesList($output, $row['id'],
                    $seprator . ' - ');

        }

        return $output;

    }

您可以為所選屬性設置單獨的條件。 例子:

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $selected = $row['id'] == $selected ? "selected='selected'" : '';
    $output .= "<option value='{$row['id']}' {$selected}>{$seprator}{$row['title']}</option>";

    $this->getCategoriesList($output, $row['id'], $seprator . ' - ');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM