0

I'm using this code:

var tempObj = {
    "noselected" : "",
    "option1": "item1",
    "option2": "item2",
    "option3": "item3"
};

$.each(tempObj, function (val, text) {
            $(this).append($('<option />', {
                value: val,
                text: text
            }));
        });

but when that code is executed I obtain the following error:

TypeError: n.createDocumentFragment is not a function
[Break On This Error]   

...eturn t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=...

And only the first element is not appended.

4

2 回答 2

3

你需要这样做 -

$.each(tempObj, function (val, text) {
    $('<option />', {
        value: val,
        text: text
    }).appendTo('select');
});

演示---> http://jsfiddle.net/zKkXp/2/

根据您的评论-您正在单击处理程序中执行此操作并尝试使用thisinside访问单击的选择each,您可以这样做-

$('select').click(function () {
    var $this = $(this);
    $.each(tempObj, function (val, text) {
        $this.append($('<option />', {
            value: val,
            text: text
        }));
    });
});

演示---> http://jsfiddle.net/zKkXp/4/

于 2013-06-16T15:31:17.883 回答
0
$.each(tempObj, function (val, text) {
    $('select').append($('<option>', { 
        value: val,
        text : text 
    }));
});
于 2013-06-16T15:33:46.640 回答