从选择中删除选项并将其添加到另一个选项

时间:2011-05-02 15:09:10

标签: jquery

好的,所以我已经有了这个代码,以前工作得很好。我最近将我的jQuery从1.4.4升级到1.5.2,显然这已经退出了工作。但是,我已经尝试了1.4.4的代码。和1.3.2它也不会在那里工作。

这确实奏效了。我无法弄清楚它为什么不是。有什么帮助吗?

编辑:开始和结束是参数,带有select元素ID的文本。


var selectedIndex = document.getElementById(start).selectedIndex; // get the selected index from the correct select box

if (selectedIndex != -1) {      // if something is selected, do the following:
       var selectedElement = document.getElementById(start).options[selectedIndex]; // get the element that's selected

       if (selectedIndex == (document.getElementById(start).options.length - 1) && selectedIndex != 0) {
           selectedIndex--; // if we're at the bottom of the list, set our selectedIndex variable to the one right before it
       }

       $("#" + start).remove(selectedElement);  // remove the selected element from the start side          
       $("#" + end).append(selectedElement);        // and add it to the end of the ending side
}

这是我想要移动的选项的一个例子 <option sortable="yes" datatype="string" value="foo" type="arbitrary">Foo</option>

我遇到的问题显然是在jQuery本身内 - 使用完整版本,<option sortable="yes" datatype="string" value="foo" type="arbitrary">Foo</option>
当我点击expr.replace is not a function [Break On This Error] expr = expr.replace( /\=\s*([^'"]])\s]/g, "='$1']" ); [jquery-latest.debug.js, line 4540] 部分时出现错误代码。

感谢。

3 个答案:

答案 0 :(得分:4)

您收到此错误是因为.remove()采用字符串选择器,如果没有提供,则删除父对象的错误。尝试

$(selectedElement).remove();

答案 1 :(得分:2)

你有没有理由使用getElementById调用?让jQuery为你做的工作......而不是使用:

$("#" + start).remove(selectedElement);  // remove the selected element from the start side          
$("#" + end).append(selectedElement);        // and add it to the end of the ending side

}

尝试使用:

$("#"+start+" option:selected").appendTo("#" + end);

它将删除/追加操作合并为一个,可以解决您的问题。

答案 2 :(得分:0)

不幸的是,<option>不是普通元素,因此可能会导致此类问题。

有关可行的代码,请参阅this question上的已接受答案。

相关问题