http://jsfiddle.net/j3oh6s3a/
For some reason appending options to a select tag doesn't select the selected='selected' attribute option, instead selects the next option in the list.
出于某种原因,将选项附加到select标记后并没有选择selected='selected'属性选项,而是选择列表中的下一个选项。
Please see the above jfiddle.
请查看上面的jfiddle。
<select id="category">
<option value='1'>Categroy 1</option>
<option value='2'>Categroy 2</option>
<option value='3'>Categroy 3</option>
</select>
<select id="sub-category">
<option value='1' data-parentid='1'>Car1</option>
<option value='2' data-parentid='1'>Car2</option>
<option selected='selected' value='3' data-parentid='1'>Car3</option>
<option value='4' data-parentid='1'>Car4</option>
<option value='5' data-parentid='1'>Car5</option>
<option value='6' data-parentid='2'>Car6</option>
<option value='7' data-parentid='2'>Car7</option>
<option value='8' data-parentid='2'>Car8</option>
<option value='9' data-parentid='3'>Car9</option>
<option value='10' data-parentid='3'>Car10</option>
<option value='11' data-parentid='3'>Car11</option>
<option value='12' data-parentid='3'>Car12</option>
</select>
$(document).ready(function(){
var allsuboptions = $('#sub-category option').remove();
var selectedOptions = allsuboptions.filter(function () {
return $(this).data('parentid').toString() === $('#category').val().toString();
});
selectedOptions.appendTo('#sub-category');
});
In the above example Car3 should be selected, but Car4 is selected after appending options to the select.
在上面的示例中,应该选择Car3,但是在将选项添加到select之后,将选择Car4。
5 个解决方案
#1
3
This is a tricky (and interesting) question.
这是一个棘手(且有趣)的问题。
If you test the fiddle on different browsers you'll see that the selected value changes: Chrome (Car4), IE (Car3), Firefox (Car5). So I have made a slight change to your fiddle to "prove a theory". You can see the changes on this link: http://jsfiddle.net/j3oh6s3a/1/. I only added a log to the filter loop so I can see the selected element in each iteration:
如果您在不同的浏览器上测试,您将看到所选的值变化:Chrome (Car4), IE (Car3), Firefox (Car5)。所以我对你的小提琴做了一点小小的改动来“证明一个理论”。您可以在这个链接上看到更改:http://jsfiddle.net/j3oh6s3a/1/。我只向过滤器循环添加了一个日志,这样我就可以在每次迭代中看到所选的元素:
if ($(this).is(":selected")) { console.log("Selected value = " + $(this).val()) };
Now this is what happens (or at least my theory): Once the selected element is removed from the list each browser will proceed however thinks adequate to determine the selected option. And in this case each browser will proceed in a different way:
现在,这就是所发生的事情(或者至少是我的理论):一旦从列表中删除所选元素,每个浏览器将继续进行,但是认为足够确定所选的选项。在这种情况下,每个浏览器将以不同的方式运行:
-
As the selected option has been removed, Chrome will select automatically (by default) the first
option
of the remaining in the list (Car4). When this option is sent to the new list, it is automatically selected as it is newer than the previous selected option. The log is: 3, 4.由于选择的选项已被删除,Chrome将自动(默认)选择列表中其余选项的第一个选项(Car4)。当这个选项被发送到新的列表时,它会被自动选择,因为它比之前的选择选项更新。log是3 4。
-
Internet Explorer does nothing, and copies each element the same way they are without caring about if they are selected or not. The original selected value will be the final selected value (Car3). The log is: 3.
Internet Explorer什么都不做,并且以相同的方式复制每个元素,而不关心它们是否被选中。原始选中的值将是最终选中的值(Car3)。日志:3。
-
Firefox will proceed like Chrome, but every time that the selected element is removed from the list, the first option of the remaining ones will be selected. The log is: 3, 4, 5, 6, 7, 8, 9, 10, 11, 12; but as the last option inserted in the list is 5, it will be the selected one.
Firefox将像Chrome一样运行,但每次从列表中删除所选元素时,将选择其余元素的第一个选项。log是3 4 5 6 7 8 9 10 11 12;但是由于列表中插入的最后一个选项是5,所以它将是选中的。
I will check later to see if I can find any information to source this, but it will have to be tomorrow as it's a bit late here.
我稍后再查,看能不能找到资料来源,但必须是明天,因为时间有点晚了。
#2
3
jQuery .remove and .append internally uses .removeChild and .appendChild methods to remove/insert the child elements.
jQuery .remove和.append内部使用. removechild和. appendchild方法来删除/插入子元素。
Theory: removeChild/appendChild maintains the attributes but doesn't maintain the element's property (maintaining the selection state)
When you use removeChild and then appendChild to add the options back, the attributes are maintained, but the property of the element are not maintained. You can read more about .prop() vs .attr() here.
当您使用removeChild和appendChild将选项添加回时,将维护属性,但不维护元素的属性。您可以在这里阅读更多关于.prop()和.attr()的内容。
In summary, attributes are initial values defined in the HTML that are parsed to set as properties to the Element by the browser, however setting the attributes doesn't guarantee setting the property.
总之,属性是HTML中定义的初始值,浏览器将其解析为元素的属性,但是设置属性并不保证设置属性。
$(function() {
var categoryDD = document.getElementById('category');
var removedOptions = remove.call(categoryDD.options);
add.call(categoryDD, removedOptions);
});
function add(options) { //add all options
for (var i = 0; i < options.length; i++) {
this.appendChild(options[i]);
}
}
function remove() { //removes all options
var el, returnOpt = [];
while (this.length) {
el = this[0];
returnOpt.push(el.parentNode.removeChild(el));
}
return returnOpt;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="category">
<option value='1'>Categroy 1</option>
<option value='2' selected="selected">Categroy 2</option>
<option value='3'>Categroy 3</option>
<option value='4'>Categroy 4</option>
<option value='5'>Categroy 5</option>
<option value='6'>Categroy 6</option>
</select>
Testing Results:
On testing the above snippet, IE 10 and FF yielded me the same result which is selecting the last option from the drop down, however chrome seems to be bugged as it always selected the next option from the original selection. The results from IE 10 and FF made a little sense as to "Not maintaining the state", however Chrome behavior seems like a bug.
在测试上面的代码片段时,IE 10和FF给出了相同的结果,从下拉菜单中选择最后一个选项,但是chrome似乎被窃听了,因为它总是从原始选项中选择下一个选项。IE 10和FF的结果对于“不保持状态”有一点意义,但是Chrome的行为看起来像一个bug。
Above is my theory based on my test case, however I couldn't find a legit reference that states the same.
以上是基于我的测试用例的理论,但是我找不到一个合法的引用。
Anyways, tryout below solutions for a consistent output.
不管怎样,尝试下面的解决方案以获得一致的输出。
Solution 1: Remove only options that are NOT equal to parentId.
解决方案1:只删除不等于parentId的选项。
$('#sub-category option').filter(function () {
return $(this).data('parentid').toString() !== $('#category').val().toString();
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="category">
<option value='1'>Categroy 1</option>
<option value='2'>Categroy 2</option>
<option value='3'>Categroy 3</option>
</select>
<select id="sub-category">
<option value='1' data-parentid='1'>Car1</option>
<option value='2' data-parentid='1'>Car2</option>
<option selected='selected' value='3' data-parentid='1'>Car3</option>
<option value='4' data-parentid='1'>Car4</option>
<option value='5' data-parentid='1'>Car5</option>
<option value='6' data-parentid='2'>Car6</option>
<option value='7' data-parentid='2'>Car7</option>
<option value='8' data-parentid='2'>Car8</option>
<option value='9' data-parentid='3'>Car9</option>
<option value='10' data-parentid='3'>Car10</option>
<option value='11' data-parentid='3'>Car11</option>
<option value='12' data-parentid='3'>Car12</option>
</select>
Solution 2: [based on your original answer] The solution is simple, just get the select value before removing the options and set the selection after using .append.
解决方案2:[基于您的原始答案]解决方案很简单,只需在删除选项之前获取select值,然后在使用.append之后设置选择。
var $subcategory = $('#sub-category');
var selectedOption = $subcategory.val();
var allsuboptions = $subcategory.find('option').remove();
var selectedOptions = allsuboptions.filter(function() {
return $(this).data('parentid').toString() === $('#category').val().toString();
});
selectedOptions.appendTo('#sub-category');
$subcategory.val(selectedOption);
<select id="category">
<option value='1'>Categroy 1</option>
<option value='2'>Categroy 2</option>
<option value='3'>Categroy 3</option>
</select>
<select id="sub-category">
<option value='1' data-parentid='1'>Car1</option>
<option value='2' data-parentid='1'>Car2</option>
<option selected='selected' value='3' data-parentid='1'>Car3</option>
<option value='4' data-parentid='1'>Car4</option>
<option value='5' data-parentid='1'>Car5</option>
<option value='6' data-parentid='2'>Car6</option>
<option value='7' data-parentid='2'>Car7</option>
<option value='8' data-parentid='2'>Car8</option>
<option value='9' data-parentid='3'>Car9</option>
<option value='10' data-parentid='3'>Car10</option>
<option value='11' data-parentid='3'>Car11</option>
<option value='12' data-parentid='3'>Car12</option>
</select>
#3
2
What you're not seeing is the difference between the "selected" property and the "selected" attribute. If you put this at the end of your code you can see it:
您看不到的是“选择”属性和“选择”属性之间的区别。如果你把这个放在代码的末尾,你可以看到:
// Attribute
console.log( $("#sub-category").find("[selected]").val() );
// Property
console.log( $("#sub-category").find(":selected").val() );
Your option with value "3" has the selected attribute, but not the property, it's the opposite for the option with value "4".
值为“3”的选项具有所选的属性,但没有属性,它与值为“4”的选项相反。
Whenever you add options inside a select, you must re-select the desired one:
无论何时在选择中添加选项,都必须重新选择所需的选项:
$("#sub-category").find("[selected]").prop("selected", true);
#4
2
Firefox selects the last element. This behavior is probably correct and explainable. In order to understand, please keep the following in mind:
Firefox选择最后一个元素。这种行为可能是正确的,而且是可以解释的。为了理解,请记住以下几点:
- jQuery append and remove methods process the elements one by one behind the scene.
- jQuery添加和删除方法处理场景后面的元素。
- The current state of an input element should be retrieved or set using the corresponding property, not attribute.
- 应该使用相应的属性(而不是属性)检索或设置输入元素的当前状态。
Expected Behavior (Firefox)
预期行为(Firefox)
Removing all options from a select element as demonstrated in your example works as follows:
从select元素中删除所有选项,如下所示:
- Car1 is removed (Car3 remains selected)
- Car1被移除(Car3仍然被选中)
- Car2 is removed (Car3 remains selected)
- Car2被移除(Car3仍然被选中)
- Car3 is removed. Since this is the selected element, removing it will cause the next element to become selected
- Car3被移除。由于这是选中的元素,删除它将导致下一个元素被选中
- Car4 is removed. Since this is the selected element, removing it will cause the next element to become selected
- Car4被移除。由于这是选中的元素,删除它将导致下一个元素被选中
This will repeat until all options are moved from DOM to the memory. At this point the options will have the following properties:
这将重复,直到所有选项从DOM移动到内存。此时,这些选项将具有以下属性:
// allsuboptions.each(function() { console.log(this.value, this.selected); });
value: 1, selected: false
value: 2, selected: false
value: 3, selected: true
value: 4, selected: true
...
value: 12, selected: true
There are 3 options with selected = true
. When you add the options back to the select element, the browser sets the last selected element as the selected one.
有3个选项选择= true。当您将选项添加回select元素时,浏览器将最后选中的元素设置为选中的元素。
Internet Explorer and Chrome
Internet Explorer和铬
While the options are removed one by one, these two browsers do not update the selected element immediately (they possibly wait for JavaScript execution to finish). This causes the following discrepancies:
当选项逐个移除时,这两个浏览器不会立即更新所选元素(它们可能等待JavaScript执行完成)。造成以下差异:
-
Internet Explorer does not immediately make the next option selected when currently selected option is removed. Therefore the removed options contain only one selected element.
当当前选择的选项被删除时,Internet Explorer不会立即选择下一个选项。因此,删除的选项只包含一个选定的元素。
-
Chrome seems to immediately make the next option selected when currently selected option is removed, but it does that only once. Therefore the removed options contain two selected elements.
当当前选择的选项被删除时,Chrome似乎会立即选择下一个选项,但它只做一次。因此,删除的选项包含两个选定的元素。
In order to prove the point about immediate and deferred updates, here is a Fiddle containing:
为了证明关于即时更新和延迟更新的观点,这里有一个小提琴包含:
- The original code
- 原始代码
- A variation that forces the browser to update the select element each time an option is removed
- 强制浏览器在每次删除选项时更新select元素的变体
http://jsfiddle.net/salman/j3oh6s3a/9/
http://jsfiddle.net/salman/j3oh6s3a/9/
Solution
解决方案
As suggested in other answers, the correct workaround is to use a variable that references the currently selected option before removing the options. Something like:
如其他答案所示,正确的解决方法是使用一个变量,在删除选项之前引用当前选择的选项。喜欢的东西:
var $selectedOption = $("#sub-category option").filter(function() {
return this.selected;
});
Once the options are re-inserted, you can check if that element was added back and select it again:
重新插入选项后,您可以检查该元素是否被添加回来并再次选择:
if ($selectedOption.parent().length) {
$selectedOption.prop("selected", true);
}
// or
$("#sub-category option").filter($selectedOption).prop("selected", true);
#5
0
Your script is doing what you created it to do.
您的脚本正在执行您创建的任务。
The reason car4 is selected, is because
选择car4的原因是
<option selected='selected' value='3' data-parentid='1'>Car3</option>
is initially selected, then you are appending
parentid='1' to the value which causes car4 to be the new selection.
首先被选中,然后将parentid='1'添加到导致car4成为新选择的值。
What is the purpose of this script?
这个脚本的目的是什么?
#1
3
This is a tricky (and interesting) question.
这是一个棘手(且有趣)的问题。
If you test the fiddle on different browsers you'll see that the selected value changes: Chrome (Car4), IE (Car3), Firefox (Car5). So I have made a slight change to your fiddle to "prove a theory". You can see the changes on this link: http://jsfiddle.net/j3oh6s3a/1/. I only added a log to the filter loop so I can see the selected element in each iteration:
如果您在不同的浏览器上测试,您将看到所选的值变化:Chrome (Car4), IE (Car3), Firefox (Car5)。所以我对你的小提琴做了一点小小的改动来“证明一个理论”。您可以在这个链接上看到更改:http://jsfiddle.net/j3oh6s3a/1/。我只向过滤器循环添加了一个日志,这样我就可以在每次迭代中看到所选的元素:
if ($(this).is(":selected")) { console.log("Selected value = " + $(this).val()) };
Now this is what happens (or at least my theory): Once the selected element is removed from the list each browser will proceed however thinks adequate to determine the selected option. And in this case each browser will proceed in a different way:
现在,这就是所发生的事情(或者至少是我的理论):一旦从列表中删除所选元素,每个浏览器将继续进行,但是认为足够确定所选的选项。在这种情况下,每个浏览器将以不同的方式运行:
-
As the selected option has been removed, Chrome will select automatically (by default) the first
option
of the remaining in the list (Car4). When this option is sent to the new list, it is automatically selected as it is newer than the previous selected option. The log is: 3, 4.由于选择的选项已被删除,Chrome将自动(默认)选择列表中其余选项的第一个选项(Car4)。当这个选项被发送到新的列表时,它会被自动选择,因为它比之前的选择选项更新。log是3 4。
-
Internet Explorer does nothing, and copies each element the same way they are without caring about if they are selected or not. The original selected value will be the final selected value (Car3). The log is: 3.
Internet Explorer什么都不做,并且以相同的方式复制每个元素,而不关心它们是否被选中。原始选中的值将是最终选中的值(Car3)。日志:3。
-
Firefox will proceed like Chrome, but every time that the selected element is removed from the list, the first option of the remaining ones will be selected. The log is: 3, 4, 5, 6, 7, 8, 9, 10, 11, 12; but as the last option inserted in the list is 5, it will be the selected one.
Firefox将像Chrome一样运行,但每次从列表中删除所选元素时,将选择其余元素的第一个选项。log是3 4 5 6 7 8 9 10 11 12;但是由于列表中插入的最后一个选项是5,所以它将是选中的。
I will check later to see if I can find any information to source this, but it will have to be tomorrow as it's a bit late here.
我稍后再查,看能不能找到资料来源,但必须是明天,因为时间有点晚了。
#2
3
jQuery .remove and .append internally uses .removeChild and .appendChild methods to remove/insert the child elements.
jQuery .remove和.append内部使用. removechild和. appendchild方法来删除/插入子元素。
Theory: removeChild/appendChild maintains the attributes but doesn't maintain the element's property (maintaining the selection state)
When you use removeChild and then appendChild to add the options back, the attributes are maintained, but the property of the element are not maintained. You can read more about .prop() vs .attr() here.
当您使用removeChild和appendChild将选项添加回时,将维护属性,但不维护元素的属性。您可以在这里阅读更多关于.prop()和.attr()的内容。
In summary, attributes are initial values defined in the HTML that are parsed to set as properties to the Element by the browser, however setting the attributes doesn't guarantee setting the property.
总之,属性是HTML中定义的初始值,浏览器将其解析为元素的属性,但是设置属性并不保证设置属性。
$(function() {
var categoryDD = document.getElementById('category');
var removedOptions = remove.call(categoryDD.options);
add.call(categoryDD, removedOptions);
});
function add(options) { //add all options
for (var i = 0; i < options.length; i++) {
this.appendChild(options[i]);
}
}
function remove() { //removes all options
var el, returnOpt = [];
while (this.length) {
el = this[0];
returnOpt.push(el.parentNode.removeChild(el));
}
return returnOpt;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="category">
<option value='1'>Categroy 1</option>
<option value='2' selected="selected">Categroy 2</option>
<option value='3'>Categroy 3</option>
<option value='4'>Categroy 4</option>
<option value='5'>Categroy 5</option>
<option value='6'>Categroy 6</option>
</select>
Testing Results:
On testing the above snippet, IE 10 and FF yielded me the same result which is selecting the last option from the drop down, however chrome seems to be bugged as it always selected the next option from the original selection. The results from IE 10 and FF made a little sense as to "Not maintaining the state", however Chrome behavior seems like a bug.
在测试上面的代码片段时,IE 10和FF给出了相同的结果,从下拉菜单中选择最后一个选项,但是chrome似乎被窃听了,因为它总是从原始选项中选择下一个选项。IE 10和FF的结果对于“不保持状态”有一点意义,但是Chrome的行为看起来像一个bug。
Above is my theory based on my test case, however I couldn't find a legit reference that states the same.
以上是基于我的测试用例的理论,但是我找不到一个合法的引用。
Anyways, tryout below solutions for a consistent output.
不管怎样,尝试下面的解决方案以获得一致的输出。
Solution 1: Remove only options that are NOT equal to parentId.
解决方案1:只删除不等于parentId的选项。
$('#sub-category option').filter(function () {
return $(this).data('parentid').toString() !== $('#category').val().toString();
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="category">
<option value='1'>Categroy 1</option>
<option value='2'>Categroy 2</option>
<option value='3'>Categroy 3</option>
</select>
<select id="sub-category">
<option value='1' data-parentid='1'>Car1</option>
<option value='2' data-parentid='1'>Car2</option>
<option selected='selected' value='3' data-parentid='1'>Car3</option>
<option value='4' data-parentid='1'>Car4</option>
<option value='5' data-parentid='1'>Car5</option>
<option value='6' data-parentid='2'>Car6</option>
<option value='7' data-parentid='2'>Car7</option>
<option value='8' data-parentid='2'>Car8</option>
<option value='9' data-parentid='3'>Car9</option>
<option value='10' data-parentid='3'>Car10</option>
<option value='11' data-parentid='3'>Car11</option>
<option value='12' data-parentid='3'>Car12</option>
</select>
Solution 2: [based on your original answer] The solution is simple, just get the select value before removing the options and set the selection after using .append.
解决方案2:[基于您的原始答案]解决方案很简单,只需在删除选项之前获取select值,然后在使用.append之后设置选择。
var $subcategory = $('#sub-category');
var selectedOption = $subcategory.val();
var allsuboptions = $subcategory.find('option').remove();
var selectedOptions = allsuboptions.filter(function() {
return $(this).data('parentid').toString() === $('#category').val().toString();
});
selectedOptions.appendTo('#sub-category');
$subcategory.val(selectedOption);
<select id="category">
<option value='1'>Categroy 1</option>
<option value='2'>Categroy 2</option>
<option value='3'>Categroy 3</option>
</select>
<select id="sub-category">
<option value='1' data-parentid='1'>Car1</option>
<option value='2' data-parentid='1'>Car2</option>
<option selected='selected' value='3' data-parentid='1'>Car3</option>
<option value='4' data-parentid='1'>Car4</option>
<option value='5' data-parentid='1'>Car5</option>
<option value='6' data-parentid='2'>Car6</option>
<option value='7' data-parentid='2'>Car7</option>
<option value='8' data-parentid='2'>Car8</option>
<option value='9' data-parentid='3'>Car9</option>
<option value='10' data-parentid='3'>Car10</option>
<option value='11' data-parentid='3'>Car11</option>
<option value='12' data-parentid='3'>Car12</option>
</select>
#3
2
What you're not seeing is the difference between the "selected" property and the "selected" attribute. If you put this at the end of your code you can see it:
您看不到的是“选择”属性和“选择”属性之间的区别。如果你把这个放在代码的末尾,你可以看到:
// Attribute
console.log( $("#sub-category").find("[selected]").val() );
// Property
console.log( $("#sub-category").find(":selected").val() );
Your option with value "3" has the selected attribute, but not the property, it's the opposite for the option with value "4".
值为“3”的选项具有所选的属性,但没有属性,它与值为“4”的选项相反。
Whenever you add options inside a select, you must re-select the desired one:
无论何时在选择中添加选项,都必须重新选择所需的选项:
$("#sub-category").find("[selected]").prop("selected", true);
#4
2
Firefox selects the last element. This behavior is probably correct and explainable. In order to understand, please keep the following in mind:
Firefox选择最后一个元素。这种行为可能是正确的,而且是可以解释的。为了理解,请记住以下几点:
- jQuery append and remove methods process the elements one by one behind the scene.
- jQuery添加和删除方法处理场景后面的元素。
- The current state of an input element should be retrieved or set using the corresponding property, not attribute.
- 应该使用相应的属性(而不是属性)检索或设置输入元素的当前状态。
Expected Behavior (Firefox)
预期行为(Firefox)
Removing all options from a select element as demonstrated in your example works as follows:
从select元素中删除所有选项,如下所示:
- Car1 is removed (Car3 remains selected)
- Car1被移除(Car3仍然被选中)
- Car2 is removed (Car3 remains selected)
- Car2被移除(Car3仍然被选中)
- Car3 is removed. Since this is the selected element, removing it will cause the next element to become selected
- Car3被移除。由于这是选中的元素,删除它将导致下一个元素被选中
- Car4 is removed. Since this is the selected element, removing it will cause the next element to become selected
- Car4被移除。由于这是选中的元素,删除它将导致下一个元素被选中
This will repeat until all options are moved from DOM to the memory. At this point the options will have the following properties:
这将重复,直到所有选项从DOM移动到内存。此时,这些选项将具有以下属性:
// allsuboptions.each(function() { console.log(this.value, this.selected); });
value: 1, selected: false
value: 2, selected: false
value: 3, selected: true
value: 4, selected: true
...
value: 12, selected: true
There are 3 options with selected = true
. When you add the options back to the select element, the browser sets the last selected element as the selected one.
有3个选项选择= true。当您将选项添加回select元素时,浏览器将最后选中的元素设置为选中的元素。
Internet Explorer and Chrome
Internet Explorer和铬
While the options are removed one by one, these two browsers do not update the selected element immediately (they possibly wait for JavaScript execution to finish). This causes the following discrepancies:
当选项逐个移除时,这两个浏览器不会立即更新所选元素(它们可能等待JavaScript执行完成)。造成以下差异:
-
Internet Explorer does not immediately make the next option selected when currently selected option is removed. Therefore the removed options contain only one selected element.
当当前选择的选项被删除时,Internet Explorer不会立即选择下一个选项。因此,删除的选项只包含一个选定的元素。
-
Chrome seems to immediately make the next option selected when currently selected option is removed, but it does that only once. Therefore the removed options contain two selected elements.
当当前选择的选项被删除时,Chrome似乎会立即选择下一个选项,但它只做一次。因此,删除的选项包含两个选定的元素。
In order to prove the point about immediate and deferred updates, here is a Fiddle containing:
为了证明关于即时更新和延迟更新的观点,这里有一个小提琴包含:
- The original code
- 原始代码
- A variation that forces the browser to update the select element each time an option is removed
- 强制浏览器在每次删除选项时更新select元素的变体
http://jsfiddle.net/salman/j3oh6s3a/9/
http://jsfiddle.net/salman/j3oh6s3a/9/
Solution
解决方案
As suggested in other answers, the correct workaround is to use a variable that references the currently selected option before removing the options. Something like:
如其他答案所示,正确的解决方法是使用一个变量,在删除选项之前引用当前选择的选项。喜欢的东西:
var $selectedOption = $("#sub-category option").filter(function() {
return this.selected;
});
Once the options are re-inserted, you can check if that element was added back and select it again:
重新插入选项后,您可以检查该元素是否被添加回来并再次选择:
if ($selectedOption.parent().length) {
$selectedOption.prop("selected", true);
}
// or
$("#sub-category option").filter($selectedOption).prop("selected", true);
#5
0
Your script is doing what you created it to do.
您的脚本正在执行您创建的任务。
The reason car4 is selected, is because
选择car4的原因是
<option selected='selected' value='3' data-parentid='1'>Car3</option>
is initially selected, then you are appending
parentid='1' to the value which causes car4 to be the new selection.
首先被选中,然后将parentid='1'添加到导致car4成为新选择的值。
What is the purpose of this script?
这个脚本的目的是什么?