【问题标题】:Removing an option from a select and adding it to another从选择中删除一个选项并将其添加到另一个
【发布时间】:2011-08-17 01:28:27
【问题描述】:

好的,所以我有这段代码,过去可以正常工作。我最近将我的 jQuery 从 1.4.4 升级到 1.5.2,显然这已经停止工作了。但是,我已经尝试了 1.4.4 的代码。和 1.3.2,它也不会在那里工作。

这确实有效。我不知道为什么不是。有什么帮助吗?

编辑:start 和 end 是参数,带有 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 本身 - 使用完整版本,
expr.replace is not a function [Break On This Error] expr = expr.replace( /\=\s*([^'"]])\s]/g, "='$1']" ); [jquery-latest.debug.js, line 4540]
当我点击代码的$.remove 部分时发生错误。

谢谢。

【问题讨论】:

  • 为什么说这行不通。我的意思是,错误是什么?
  • HTML 是动态生成的。使用选项和错误更新了 OP。真不敢相信我忘了提到问题到底是什么。

标签: jquery


【解决方案1】:

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

$(selectedElement).remove();

【讨论】:

  • 但是为什么这曾经有效?这就是我的困惑。这曾经可以正常工作 - 我已向我要删除的元素添加了一个 ID,并将其传递到 .remove() 的参数中,但它没有出错,它什么也不做。我会试一试。
  • 我们不能只使用 $(selectedElement).remove(); ?
  • 就是这样。嘎。谢谢。我只是不知道为什么这在所有版本的 jQuery 中都可以正常工作并随后停止。
【解决方案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);

它将删除/附加操作合二为一,可能会解决您的问题。

【讨论】:

  • 调用 getElementById 的原因是为了获取某些值,例如选定的索引。这是我的一个早期的 jQuery 项目,我并没有真正使用这样的过滤器。我也会试一试。
【解决方案3】:

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

请参阅this question 上接受的答案以获取应该可以工作的代码。

【讨论】:

  • 是的,<option> 一直很痛苦,尤其是在处理 IE 和其他所有浏览器之间的差异时 - 我只是很困惑为什么它停止工作,而它曾经停止工作。
  • @tjs 好问题.. 你试过其他问题中的代码了吗?
  • 没有具体使用过,但这里接受的答案非常相似,让我走了。我只是不知道 A)为什么它停止工作,以及 B)为什么没有其他人在我之前发现它(它被使用的地方)。
  • 是的,不。不知道。我知道它工作了几个月,但我不知道它在什么时候坏了。
猜你喜欢
  • 1970-01-01
  • 2012-08-05
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多