数组的最后一个单元格中的不需要的对象

时间:2012-05-12 22:03:56

标签: javascript jquery

我在解析的XML数组上使用以下代码:

$(this).find("cp_group").each(function() {
    $("select#comp_1").append('<optgroup label="' + $(this).attr('label') + '"><option>' + $(this).find("cmp").map(function() {
        return $(this).text();
    }).get().join("</option><option>") + $(this).append('</option></optgroup>'));
});​

我在每个选项组的最后一个选项中得到了一个不需要的[object Object],如下所示:

<select name="comp_1" id="comp_1">
<optgroup label="Combat">
<option>Arme</option>
<option>Arts martiaux</option>
<option>Esquive</option>
<option>Feinte</option>
<option>Parade</option>
<option>Lutte[object Object]</option>

我不明白这个[object Object]来自哪里,我没有实现不能得到它或删除它。 谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

它来自+ $(this).append(...)。你只需要+'</option....'部分,没有那个jQuery包装器。

答案 1 :(得分:1)

你误解了jQuery,特别是append是如何工作的。当你使用jQuery操作事物时,你没有处理标记(很大程度上),你正在处理对象(DOM元素)。

这应该解决它:

$(this).find("cp_group").each(function() {
    // Get this entry
    var $this = $(this);

    // Create the optgroup
    var optgroup = $('<optgroup label="' + $this.attr('label') + '">');

    // Fill it in
    $this.find("cmp").each(function() {
        $("<option>").text($(this).text()).appendTo(optgroup);
    });

    // Append it to the select
    $("select#comp_1").append(optgroup);
});​