如何操作两个 select 字段并动态更改 textContent

How to manipulate two select fields and dynamically change textContent

我有两个选择。 第一个显示 male of fem,第二个显示名称取决于选择的 malfem 选项。它运作良好。但我想在新 div 中显示这些值。但是,我只能访问 malfem 选项。我想这是因为它是这个。但是如何给这个 textContent 添加一个名字呢?例如,使用 textContent male Jamesfem Lola 创建一个 div ?请参阅下面的代码和 link

const namesArr = {
     male: ['Tom', 'James', 'John', 'Jimmy', 'Angelo', 'Patrick', 'Ron'],
     fem: ['Jemma', 'Samantha', 'Lola', 'Penny', 'Mary']
 }

function show(){  
    document.querySelector('#name').textContent = ''
    document.querySelector('.result').textContent = ''

 let val = this.value

  for(let i of Object.keys(namesArr)) {

    if(val === i) {

   namesArr[i].forEach(elem => {
         newElem.value = i
         newElem.textContent = elem;
         document.querySelector('#name').style.display = 'inline-block'
         document.querySelector('#name').append(newElem)             
         document.querySelector('.result').textContent = 
         this.options[this.selectedIndex].textContent               
       });
     }
  }
}
document.querySelector('#sex').addEventListener('click', show);

Link to JSFiddle

也需要添加事件侦听器名称select

jsfiddle

const namesArr = {
  male: ['Tom', 'James', 'John', 'Jimmy', 'Angelo', 'Patrick', 'Ron'],
  fem: ['Jemma', 'Samantha', 'Lola', 'Penny', 'Mary']
}

function show(){  
   document.querySelector('#name').textContent = ''
   document.querySelector('.result').textContent = ''
 
  let val = this.value
 
      for(let i of Object.keys(namesArr)) {
    
       if(val === i) {
   
       namesArr[i].forEach(elem => {
           let newElem = document.createElement('option');
           newElem.value = i
           newElem.textContent = elem;
          document.querySelector('#name').style.display = 'inline-block'
          document.querySelector('#name').append(newElem)   
            
          document.querySelector('.result').textContent = this.options[this.selectedIndex].textContent   
            
           });
       }
    }
}
function nameChange(){
var sexDDL = document.getElementById("sex");
var sex = sexDDL.options[sexDDL.selectedIndex].text;
 document.querySelector('.result').textContent = sex +" "+this.options[this.selectedIndex].textContent 
}
document.querySelector('#name').addEventListener('click', nameChange);

document.querySelector('#sex').addEventListener('click', show);
<select name="sex" id="sex">
  <option value="male">Male</option>
  <option value="fem">Feminine</option>
</select>
<select name="name" id="name"></select>

<div class="result"></div>