自定义jQuery Mobile选择菜单中的图标

时间:2012-04-23 21:12:59

标签: jquery-mobile

我正在使用jQuery Mobile的自定义选择菜单,我想将图标放入自定义弹出菜单中以配合每个option。我将data-icon属性应用于每个option,如下所示:

<select name='mySelect' id='mySelect' data-icon='gear'>
    <option value='0' data-icon='star'>Option 0</option>
    <option value='1' data-icon='star'>Option 1</option>
    <option value='2' data-icon='star' selected="selected">Option 2</option>
</select>

FWIW,我已经确认我的自定义图标在选择按钮本身中有效。我希望图标出现在自定义菜单中,我完全错了吗?

1 个答案:

答案 0 :(得分:4)

默认情况下不支持此功能,但这里有一段快速代码可以实现:

//wait for the correct page to initialize
$(document).delegate('#home', 'pageinit', function () {

    //loop through each of the SELECT elements in this page
    $.each($(this).find('select'), function () {

        //get the ID of this select because it's menu's ID is based off of it
        var currentID = this.id;

        //iterate through each of the OPTION elements for this SELECT element
        $.each($(this).find('option'), function (index, element) {

            //if the OPTION element has the `data-icon` attribute
            if ($(element).attr('data-icon') != undefined) {

                //update the menu for this SELECT by adding an icon SPAN element
                //to each of the OPTION elements that has a `data-icon` attribute
                $('#' + currentID + '-menu').children().eq(index).find('.ui-btn-inner').append('<span class="ui-icon ui-icon-' + $(element).attr('data-icon') + ' ui-icon-shadow" />');
            }
        });
    });
});​​

以下是演示:http://jsfiddle.net/NHQGD/