[英]JQuery to Remove a Selected Option in A DropDown from other DropDowns , stops working and hangs
I am using the following javascript to remove a option selected in DropDown A , from DropDown B. 我正在使用以下JavaScript从DropDown B中删除在DropDown A中选择的选项。
$('#A').bind('keypress', function(e){
if ( e.which == 52 ){
var selectedItems = $('#A').val();
var $list = $("#B"),
toRemove = $(),
selectedItems = $("#A").val();
for ( var i = 0 ; i < selectedItems.length; i++) {
toRemove = toRemove.add($list.find('option[value="' + selectedItems[i] + '"]'));
}
toRemove.remove();
}
});
The option is removed from DropDown B , but , the javascript hangs out when I press the key. 该选项已从DropDown B中删除,但是,当我按键时,javascript会挂出。 Please help.
请帮忙。
Is there some other jquery ? 还有其他的jQuery吗?
I can't explain why everything is hanging, but I think there are some things that could be improved in your code. 我无法解释为什么一切都挂起了,但是我认为您的代码中有一些可以改进的地方。
If you have a "dropdown" then the select element will be single-select, which means the .val()
method will be returning a string rather than an array (it only returns an array in the case of a <select multiple="multiple">
element), and if it's returning a string you don't need the for loop because - well, there's nothing to loop through. 如果您有一个“下拉列表”,则select元素将是单选的,这意味着
.val()
方法将返回字符串而不是数组(仅在<select multiple="multiple">
的情况下返回数组) <select multiple="multiple">
)元素),并且如果它返回一个字符串,则不需要for循环,因为-嗯,没有循环可做。 If that is true the simplified version of your code would be this: 如果是这样,则您的代码的简化版本应为:
$('#A').bind('keypress', function(e){
if ( e.which === 52 ){
$('#B option[value="' + $(this).val() + '"]').remove();
}
});
If there is no matching option in #B for the selected item then nothing will happen. 如果#B中没有与所选项目匹配的选项,则不会发生任何事情。
I don't understand the significance of key code 52, but I've left that in. 我不了解键控代码52的重要性,但我没有提及。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.