如何将 toState 和 fromState 附加选项作为子项

How to make both toState and fromState append option as a Child

toState appends 和 fromState 应该作为 child append option,但目前只有 State that comes last appends。如果 fromState 最后出现,它会附加选项作为子项,但 toState 不会附加选项,反之亦然

  response.json().then(function (data) {
    // Get States ID of to and from
    let toState = document.getElementById('to-state');
    let fromState = document.getElementById('from-state');

    for (let i = 0; i < data.states.length; i++) {

      let option = document.createElement('option');
      option.text = data.states[i].name;
      option.value = data.states[i].id;
      toState.appendChild(option)
      fromState.appendChild(option)

    }

  });

查看 Node.appendChild() 的文档:

If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position

This means that a node can't be in two points of the document simultaneously.

因此,您第二次调用 appendChild() 时,节点从其先前的父节点移动到新的父节点,即从 to-state 移动到 from-state,反之亦然。为了将相同的子节点附加到两个父节点,您需要克隆它:

toState.appendChild(option);
fromState.appendChild(option.cloneNode(true));

参数true告诉cloneNode()制作其子树的完整副本。