JQM(jQueryMobile)动态添加未正确显示的元素,并且未应用CSS

时间:2011-03-09 16:54:13

标签: jquery html css dynamic jquery-mobile

我遇到动态添加select标记的问题,CSS和其他html标记(JQM添加)都没有被应用。

以下是我添加新选择标记的示例:http://jsfiddle.net/UcrD8/4/

HTML:

<div data-role="page" id="page_1">
    <div id="select_option_groups">
        <div data-role="fieldcontain">
            <select name="select_options_1">
                <option value="" selected>Please select an option</option>
                <option value="foo">Foo</option>
                <option value="bar">Bar</option>
            </select>
        </div>
    </div>
</div>

JS:

$(function(){
    var counter = 2;
    var onChange = function(e){
        val = $(':selected',this).val() || '';
        if (val != ''){
            // they may be able to toggle between valid options, too.
            // let's avoid that using a class we can apply
            var c = 'alreadyMadeASelection';
            if ($(this).hasClass(c))
                return;
            // now take the current select and clone it, then rename it
            var newSelect = $(this)
                .clone()
                .attr('name','select_options_'+counter)
                .attr('id','select_options_'+counter)
                .appendTo('#select_option_groups')
                .change(onChange);
            $(this).addClass(c);
            counter++;
        } else {
            var id = $(this).attr('name').match(/\d+$/), parent = $(this).parent();
            $(this).remove();

            // re-order the counter (we don't want missing numbers in the middle)
            $('select',parent).each(function(){
                var iid = $(this).attr('name').match(/\d+$/);
                if (iid>id)
                    $(this).attr('name','select_options_'+(iid-1));
            });
            counter--;
        }
    };
    $('#select_option_groups select').change(onChange);
});

我试过了:

// this gets the select tags to stack but still no CSS
$(newSelect).fieldcontain('refresh'); 

// does nothing
$(newSelect).page();

// does nothing
$('#page_1').page();

3 个答案:

答案 0 :(得分:4)

试试这个:

$(newSelect).selectmenu('refresh');

或者这会强制重建它:

$(newSelect).selectmenu('refresh', true);

如果有效,请告诉我。

答案 1 :(得分:3)

我不知道为什么.selectmenu('refresh');不起作用,但对于页面 - 您可以在元素上使用它一次。之后,它会在下次跳过该元素。

  1. 在添加内容之前克隆选择(克隆不带参数)
  2. 删除原始
  3. 将内容添加到克隆元素
  4. 把它放回dom
  5. 在其上调用.page().selectmenu(),或在包含它的元素上调用.page()
  6. 应该有所帮助。 如果没有,那么尝试从头开始创建一个新的select元素,并使用原始的选项加载它,然后添加新的选项,然后继续。

    [编辑]

    以上只是猜测。你的代码就是这样。只需要拨打.selectmenu()一个电话 工作代码:

    http://jsfiddle.net/UcrD8/45/

答案 2 :(得分:1)

应在要正确呈现的对象的父级上使用.trigger(“create”)。

检查以下链接:

http://demos.jquerymobile.com/1.3.2/faq/injected-content-is-not-enhanced.html

以下答案: https://stackoverflow.com/a/11054451/487812