【问题标题】:JHTML generic list add data attributes to options Joomla 2.5JHTML 通用列表将数据属性添加到选项 Joomla 2.5
【发布时间】:2013-06-13 10:59:45
【问题描述】:

我需要在 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" 添加到每个选项?

谢谢

【问题讨论】:

  • 不想这么说,但是 JHtmlSelect::option() 没有任何规定可以添加这个。
  • 很酷的功能创意,但我认为现在你需要扩展它。
  • 同意上述观点,您可能不得不自己动手。 JHTML 的注册功能允许您添加自己的选项。
  • 好的,看来我得扩展它了。谢谢大家!

标签: joomla joomla2.5


【解决方案1】:

事实上是可能的:

$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() 设置一个选项时,我已经扩展了 JHtmlSelect 并覆盖了 genericlist()'option.attr'。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 2016-07-30
    • 2017-08-25
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多