在建立 HTML 表格的類別中,我有這個呈現表格的方法。除了某些條件下的 HTML 屬性分配之外,一切都正常運作(縮排、結束標籤、資料表示等)。當我設定單元格資料時,我會呼叫 setData() 來接收三個參數並像這樣使用它。注意我如何設定第三個參數(單元格屬性):
方法定義:
public function setData( array $data, array $row_attributes = [], array $cell_attributes = [] ): bool { // the code }
通話:
$table->setData( $pagination->resultset, [], // row attributes array( // cell attributes array(), // row 1 (index 0) array( // row2 (index 1) ["id"=>"R2C1id"], // row 2, cell 1 ["id"=>"R2C2id", "onclick"=>"R2C2_onclick();"], // row 2, cell 2 ), array( // row 3 [], [], ["id"=>"R3C3id", "selected"=>"selected"], // row 3, cell 3 [], [], [], [] ) ) );
在此範例中,表格有七個欄位。
在這裡您將看到 HTML 輸出。注意第二行和第三行的單元格屬性:
1Consumidor FinalConsumidor Final12Prueba SRLTu Prueba1234567890113Otra Prueba SAPrueba 2123456789021
這是我用來完成這一切的程式碼。我將向您展示單元格渲染的程式碼片段以及處理屬性的方法。
儲存格渲染:
// process cells $row_counter = 0; foreach ($this->data as $data) { // row $row_build = ""; $cell_counter = 0; foreach ($data as $cell_data) { // cell if ($cell_counter < $col_count) { $row_build .= $this->getHtmlDiv( $html_cell_class, $cell_data ?? "", $this->getHtmlAttributes("cell", $row_counter, $cell_counter), 3 ); } $cell_counter ; } // $cell_counter ; // complete empty cells to preserve row:hover on full row while ($cell_counter < $col_count) { $row_build .= $this->getHtmlDiv( $html_cell_class, "", $this->getHtmlAttributes("cell", $row_counter, $cell_counter), 3 ); $cell_counter ; } $body_build .= $this->getHtmlDiv( $html_row_class, $row_build, $this->getHtmlAttributes("row", $row_counter, 0), 2, true ); $row_counter ; }
屬性的方法:
private function getHtmlAttributes(string $section, int $row, int $column): array { if (count($this->html_attributes[$section]) > 0) { if (array_key_exists($row, $this->html_attributes[$section])) { if ($section === "cell") { if (array_key_exists($column, $this->html_attributes[$section][$row])) { return $this->html_attributes[$section][$row][$column]; } } return $this->html_attributes[$section][$row]; } } return []; }
怎麼了?謝謝。
好吧,當我發布問題並選擇程式碼時,答案出現了。在方法
getHtmlAttributes()
中,缺少else
條件。