我写了一些代码来获取 <select>
来自 Json 文件的 s。我的代码根据可用的 Json 级别生成新的选择:我有第一个选择,如果选择的选项有第二个连接的选项,一个新的 <select>
出来了它的选择。它继续前进,直到我到达树的“叶子”。到目前为止一切都很好。无论如何,如果我更改前一个选择的选项,我会在最新的选项上附加一个选项。相反,我需要的是根据我所做的前一个选项的更改来更改最新选项的值。
示例
1 --> 1.1 --> 1.1.1 如果我把“1.1”变成“1.2”
我得到:1 --> 1.2 --> 1.1.1 --> 1.2.1 。
我想要得到的是:1 --> 1.2 --> 1.2.1
最佳答案
是的,我有第二个解决方案。使用 Date().getTime() 的 UTC 毫秒作为 ID。每个新<select>
将始终具有比您单击的 ID 更大的 ID。应该以相同的方式工作,而不必被迫调整 optionIds。我将所有 ID 改回 5 位数长度。
function createSelect(source) {
var select = $('<select>');
// add an additional field in order to be able to choose all real options from start
var headline = $('<option>').attr('value', 0).html('-- choose --');
select.append(headline);
// for-loop
// the current UTC-millisecs become the ID
select.attr('id', new Date().getTime());
select.change(function() {
// Get the ID of the current select
const currentID = Number(this.id);
// remove every element from DOM that has a larger id
$( "select" ).each( function(index, element) {
let otherID = Number(element.id);
if(otherID > currentID) {
document.getElementById(this.id).remove();
}
});
// the rest of your code ...
关于javascript - 当我更改选项时将 <select> 与来自 json 的数据连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51111175/