Laravel,为选择下拉列表中的选项添加不同的html属性

有没有办法在下拉选择中使用刀片Form::select()将HTML属性添加到选项?

好吧,因为我需要这样的东西:(在option标签中添加不同的CSS类)

  blue red yellow  

UPDATE (CSS类名称不应与文本名称相同.css类来自数据库中的表。)

  colors-blue something-red banana is yellow  

如果它只是一个CSS类添加到所有这些选项,我可以简单地使用jQuery。 但我需要添加多个。

PS:我将类名存储在数据库的表中。

从文档中 ,我看不到任何光明。 我也看过API。

更新2 (提供更多代码细节)

 // In my create view I have this: {{ Form::select( 'colored_stuffs', $colorsList, null, ['id'=>'colored_stuffs'] ) }} // The $colorsList generate an array in the ColorsController@create public function getCreate() { $colorsList = $this->colors->listAll(); } // listAll() is defined here is this repository public function listAll() { $colors = $this->model->lists('name', 'id', 'color_class'); return $colors; } // the HTML optput of the create view it's this  Red is used to alert something A banana is yellow Sorry no color here  // But I want this  Red is used to alert something A banana is yellow Sorry no color here  

默认的Form::select()帮助程序不支持您请求的内容,但您可以使用宏添加其他Form帮助程序 :

 Form::macro('fancySelect', function($name, $list = array(), $selected = null, $options = array()) { $selected = $this->getValueAttribute($name, $selected); $options['id'] = $this->getIdAttribute($name, $options); if ( ! isset($options['name'])) $options['name'] = $name; $html = array(); foreach ($list as $list_el) { $selectedAttribute = $this->getSelectedValue($list_el['value'], $selected); $option_attr = array('value' => e($list_el['value']), 'selected' => $selectedAttribute, 'class' => $list_el['class']); $html[] = 'html->attributes($option_attr).'>'.e($list_el['display']).''; } $options = $this->html->attributes($options); $list = implode('', $html); return "{$list}"; }); 

您可以根据需要将此新方法与其他class使用:

 $options = [ [ 'value' => 'value-1', 'display' => 'display-1', 'class' => 'class-1' ], [ 'value' => 'value-2', 'display' => 'display-2', 'class' => 'class-2' ], [ 'value' => 'value-3', 'display' => 'display-3', 'class' => 'class-3' ], ]; echo Form::fancySelect('fancy-select', $options); 

不再需要创建宏。 从LaravelCollective 5.4开始,您可以将第5个参数与所有选项的各个属性一起使用。

 {{ Form::select('name', $list, null, ['id'=>'colored_stuffs'], [1 => ['color' => 'blue'], 2 => ['color' => 'red'], 3 => ['color => 'yellow]) }} 

您可以使用它来添加自定义数据 – *属性或标准属性,如禁用。

您可以遍历该选项,然后使用其文本添加为​​类:

 $('#colors option').each(function(){ $(this).addClass($(this).text()); }); 
 $colors = array("green","blue","red"); echo ''; 

更新

 $('#colors option').each(function(){ color = $(this).text().split("-")[1]; $(this).addClass(color); }); 
 $('#colors option').each(function(){ color = $(this).text().split("-")[1]; $(this).addClass(color); }); 
 .blue{ color:blue; } .yellow{ color:yellow; } .red{ color:red; } 
   

这很容易,只需要确保使用class作为第四个 paramneter

$ yourArray = array(); 使用{{Form :: select(’cat_id’,$ yourArray,”,[‘class’=>’form-control’])}}