4

我需要将数据属性添加到 Joomla 2.5 中的 JHtml 通用列表中的各个选项。

在标准 html 中,选择列表如下所示:

<select class="field" placeholder="<?php echo JText::_('COUNTRY')?>" name="country" id="country" autofocus="autofocus" autocorrect="off" autocomplete="off">
    <option value="" selected="selected">Select Country</option>
    <option value="Afghanistan" data-alternative-spellings="AF">Afghanistan</option>
    <option value="Åland Islands" data-alternative-spellings="AX Aaland Aland" data-relevancy-booster="0.5">Åland Islands</option>
    <option value="Albania" data-alternative-spellings="AL">Albania</option>
...
</select>

通常在创建选项时我会这样做:

$options=array();
$options[]=JHTML::_( 'select.option', "Afghanistan", "Afghanistan" );
$options[]=JHTML::_( 'select.option', "Albania", "Albania" );
...

 $dropdown = JHTML::_('select.genericlist',$options,'country','id="country" autofocus="autofocus" autocorrect="off" autocomplete="off"','value','text',$default);

如何将 data-alternative-spellings="AF" 添加到每个选项?

谢谢

4

1 回答 1

13

事实上是可能的:

$data = array(
    array(
        'value' => 'redapple',
        'text' => 'Red apple',
        'attr' => array('data-price'=>'5'),
    ),
    array(
        'value' => 'greenapple',
        'text' => 'Green apple',
        'attr' => array('data-price'=>'3'),
    ),
);

$options = array(
    'id' => 'applesfield', // HTML id for select field
    'list.attr' => array( // additional HTML attributes for select field
        'class'=>'field-apples',
    ),
    'list.translate'=>false, // true to translate
    'option.key'=>'value', // key name for value in data array
    'option.text'=>'text', // key name for text in data array
    'option.attr'=>'attr', // key name for attr in data array
    'list.select'=>'greenapple', // value of the SELECTED field
);

$result = JHtmlSelect::genericlist($data,'apples',$options);

这将导致:

<select id="applesfield" name="apples" class="field-apples">
    <option value="redapple" data-price="5">Red apple</option>
    <option value="greenapple" data-price="3" selected="selected">Green apple</option>
</select>

说明:当我发现我真的需要为 genericlist(): 'option.attr'设置一个选项时,我已经扩展了JHtmlSelect并覆盖了genericlist()

JHtmlSelect::genericlist() 的参数相当复杂,但很简单:如果第三个参数是数组并且它是您传递的最后一个参数,它将用于填充genericlist 的选项。

'option.attr'将为您的选项的额外属性设置。如果设置了此项,您可以根据需要向选项添加任意数量的属性,如上面的$data数组所示。

于 2014-01-17T15:05:59.013 回答