Vanilla JavaScript:<dropdown select =“”> option.remove(Index)如何工作?

时间:2018-09-08 17:17:13

标签: javascript html drop-down-menu html-select

我正在创建一个包含两个菜单的从属下拉菜单。

只要更改第一个菜单中的选项,第二个菜单的内容就必须更改。

我遵循了2个步骤:

第1步:从第二个菜单中删除所有选项

第2步:根据第一个菜单中选择的选项,为第二个菜单重新填充。

要删除所有选项,我已经编写了以下代码:

var select = document.getElementById('1st_select');
var selected = select.value;
var target = document.getElementById('2nd_select');
var targetLength = target.length
console.log("Length"+target.length);
for (var i = 0; i <targetLength; i++) {
    console.log(i);
    target.remove(i);
}

以上代码无法达到目的。更改第一个菜单中的选项后,某些选项会保留在第二个下拉菜单中。

但是如果我只是从

更改遍历循环
for (var i = 0; i <targetLength; i++)

for (var i = targetLength; i >=0; i--)

它工作正常。

为什么会这样?

请尝试仅在Pure / Vanilla Javascript中解释该概念。

代码片段,用于循环遍历故障。

function show_op(id,lb){
    var ops = document.getElementsByClassName('option-contents');
	var op = document.getElementById(id);
	for (var i = 0; i < ops.length; i++) {
		ops[i].style.display='none';
	}
	op.style.display='block';
	var labels = document.getElementsByClassName('option-links');
	var label = document.getElementById(lb);
	for (var i = 0; i < labels.length; i++) {
		labels[i].style.backgroundColor="transparent";
	}
	label.style.backgroundColor="#cccccc";
}

var productsByCategory = {
    A: ["CNC 1", "CNC 2", "CNC 3", "CNC 4"],
    B: ["LASER 1", "LASER 2", "LASER 3", "LASER 4"],
    C: ["RUBBER 1", "RUBBER 2", "RUBBER 3", "RUBBER 4", "RUBBER 5"],
    D: ["PRECISION 1","PRECISION 2","PRECISION 3"]
}
var valuesByCategory = {
    A: ["A1", "A2", "A3", "A4"],
    B: ["B1", "B2", "B3", "B4"],
    C: ["C1", "C2", "C3", "C4", "C5"],
    D: ["D1","D2","D3"]
}
console.log(productsByCategory);
console.log(productsByCategory['A']);
for (var i in productsByCategory['B']){
console.log(productsByCategory['B'][i]);
}
function dropdown(){
	var select = document.getElementById('1st_select');
	var selected = select.value;
	var target = document.getElementById('2nd_select');
	var targetLength = target.length
	console.log("Length"+target.length);
	for (var i = 0; i <targetLength; i++) {
		console.log(i);
		target.remove(i);
	}
	if (selected==0) {
		var option = document.createElement("option");
		option.text="Select Product first";
		option.value="";
		target.add(option);
	}
	if (selected==1) {
		
		for (var i in productsByCategory['A']){
			var option = document.createElement("option");
			option.text=productsByCategory['A'][i];
			option.value=valuesByCategory['A'][i];
			target.add(option);
		}
		
	} 

	else if (selected==2){
		for (var i in productsByCategory['B']){
			var option = document.createElement("option");
			option.text=productsByCategory['B'][i];
			option.value=valuesByCategory['B'][i];
			target.add(option);
		}
	}
	else if (selected==3){
		for (var i in productsByCategory['C']){
			var option = document.createElement("option");
			option.text=productsByCategory['C'][i];
			option.value=valuesByCategory['C'][i];
			target.add(option);
		}
	}
	else {
		for (var i in productsByCategory['D']){
			var option = document.createElement("option");
			option.text=productsByCategory['D'][i];
			option.value=valuesByCategory['D'][i];
			target.add(option);
		}
	}
}
function dropdown2(){
	var select = document.getElementById('2nd_select');
	var selected = select.value; 
	console.log(selected);
}
body{
    height: 100vh;
	margin: 0px;
	overflow-y: auto;
	font-family: 'Roboto';
}
#clear{
 	clear: both;
}
.content{
	display: flex;
	background-color: white;
	height: auto;
	margin-top: 0px;
	font-family: 'Roboto';
	z-index: -1;
	min-height: 88%;
}

.links{
	position: relative;
	display: block;
	float: left; 
	width: 30%;
	border-style: solid;
	box-sizing: border-box;
	border-color: black;
	line-height: 3;	
}
.link-contents{
	position: relative;
	display: block;
	float: left;
	left: 0px;
	width: 70%;
	border-style: solid;
	box-sizing: border-box;
	border-color: red;
	
}
.option-links{
	display: block;
	font-size: 30px;
	cursor: pointer;

}
#op1{
	background-color: #cccccc;
}

.footer{
	display: block;
	max-height: 4%;
}


#order_now{
	display: block;
}
<!DOCTYPE html>
<html>
<head>
	<link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet'>
	<link rel="stylesheet" type="text/css" href="profile.css">
	<title></title>
</head>
<body>
<div class="content">
		<div class="links">
			<span class="option-links" id="op1" onclick="show_op('order_now','op1');">Order new</span><br/>
		</div>
		<div class="link-contents">
			<div class="option-contents" id="order_now">
				<select id="1st_select" onchange="dropdown();">
					<option value="0">Select</option>
					<option value="1">CNS</option>
					<option value="2">Laser Cut</option>
					<option value="3">Rubber roller</option>
					<option value="4">Fixture</option>
				</select>

				<select id="2nd_select" onchange="dropdown2();">
					<option>Select Product first</option>
				</select>
				
			</div>
		</div>
	
		<div id="clear"></div>

	</div>
		
	<div class="footer">
		A big thank you to all of you.
	</div>
	
	

</body>
<script type="text/javascript" src="profile.js"></script>
</html>

3 个答案:

答案 0 :(得分:2)

删除此代码段

for (var i = 0; i < targetLength; i++) {
    console.log(i);
    target.remove(i);
  }

带有target.innerHTML='';,它将清空第二个下拉菜单,并添加新的选项

function show_op(id, lb) {
  var ops = document.getElementsByClassName('option-contents');
  var op = document.getElementById(id);
  for (var i = 0; i < ops.length; i++) {
    ops[i].style.display = 'none';
  }
  op.style.display = 'block';
  var labels = document.getElementsByClassName('option-links');
  var label = document.getElementById(lb);
  for (var i = 0; i < labels.length; i++) {
    labels[i].style.backgroundColor = "transparent";
  }
  label.style.backgroundColor = "#cccccc";
}

var productsByCategory = {
  A: ["CNC 1", "CNC 2", "CNC 3", "CNC 4"],
  B: ["LASER 1", "LASER 2", "LASER 3", "LASER 4"],
  C: ["RUBBER 1", "RUBBER 2", "RUBBER 3", "RUBBER 4", "RUBBER 5"],
  D: ["PRECISION 1", "PRECISION 2", "PRECISION 3"]
}
var valuesByCategory = {
  A: ["A1", "A2", "A3", "A4"],
  B: ["B1", "B2", "B3", "B4"],
  C: ["C1", "C2", "C3", "C4", "C5"],
  D: ["D1", "D2", "D3"]
}
console.log(productsByCategory);
console.log(productsByCategory['A']);
for (var i in productsByCategory['B']) {
  console.log(productsByCategory['B'][i]);
}

function dropdown() {
  var select = document.getElementById('1st_select');
  var selected = select.value;
  var target = document.getElementById('2nd_select');
  var targetLength = target.length
  console.log("Length" + target.length);
  target.innerHTML = ''; //changed here
  /*for (var i = 0; i < targetLength; i++) {
    console.log(i);
    target.remove(i);
  }*/
  if (selected == 0) {
    var option = document.createElement("option");
    option.text = "Select Product first";
    option.value = "";
    target.add(option);
  }
  if (selected == 1) {

    for (var i in productsByCategory['A']) {
      var option = document.createElement("option");
      option.text = productsByCategory['A'][i];
      option.value = valuesByCategory['A'][i];
      target.add(option);
    }

  } else if (selected == 2) {
    for (var i in productsByCategory['B']) {
      var option = document.createElement("option");
      option.text = productsByCategory['B'][i];
      option.value = valuesByCategory['B'][i];
      target.add(option);
    }
  } else if (selected == 3) {
    for (var i in productsByCategory['C']) {
      var option = document.createElement("option");
      option.text = productsByCategory['C'][i];
      option.value = valuesByCategory['C'][i];
      target.add(option);
    }
  } else {
    for (var i in productsByCategory['D']) {
      var option = document.createElement("option");
      option.text = productsByCategory['D'][i];
      option.value = valuesByCategory['D'][i];
      target.add(option);
    }
  }
}

function dropdown2() {
  var select = document.getElementById('2nd_select');
  var selected = select.value;
  console.log(selected);
}
body {
  height: 100vh;
  margin: 0px;
  overflow-y: auto;
  font-family: 'Roboto';
}

#clear {
  clear: both;
}

.content {
  display: flex;
  background-color: white;
  height: auto;
  margin-top: 0px;
  font-family: 'Roboto';
  z-index: -1;
  min-height: 88%;
}

.links {
  position: relative;
  display: block;
  float: left;
  width: 30%;
  border-style: solid;
  box-sizing: border-box;
  border-color: black;
  line-height: 3;
}

.link-contents {
  position: relative;
  display: block;
  float: left;
  left: 0px;
  width: 70%;
  border-style: solid;
  box-sizing: border-box;
  border-color: red;
}

.option-links {
  display: block;
  font-size: 30px;
  cursor: pointer;
}

#op1 {
  background-color: #cccccc;
}

.footer {
  display: block;
  max-height: 4%;
}

#order_now {
  display: block;
}
<div class="content">
  <div class="links">
    <span class="option-links" id="op1" onclick="show_op('order_now','op1');">Order new</span><br/>
  </div>
  <div class="link-contents">
    <div class="option-contents" id="order_now">
      <select id="1st_select" onchange="dropdown();">
        <option value="0">Select</option>
        <option value="1">CNS</option>
        <option value="2">Laser Cut</option>
        <option value="3">Rubber roller</option>
        <option value="4">Fixture</option>
      </select>

      <select id="2nd_select" onchange="dropdown2();">
        <option>Select Product first</option>
      </select>

    </div>
  </div>

  <div id="clear"></div>

</div>

<div class="footer">
  A big thank you to all of you.
</div>

答案 1 :(得分:1)

这是因为使用for (var i = 0; i <targetLength; i++),目标数组中位于索引i处的选项被替换为i + 1处的选项(因此后面有1个选项)。

例如; 第一次i = 0时,您将其删除,target.delete(i)将为target.delete(0) 这将删除索引0处的选项,但索引1(i 1)处的选项现在移至0;然后JS将前进到下一个循环,在该循环中我变为1,因此跳过后面的选项。

当您从i = targetlength开始时,它将在每个循环中删除最后一个索引,因此不会在目标数组中移动您的选项;

答案 2 :(得分:1)

select删除元素时,以下所有选项都会重新索引。因此,如果您在remove(i)时执行i = 3,则带有index = 4的选项将变为index = 35将会变为4,依此类推。

然后,循环将递增i,因此下一次迭代将删除4。此选项最初是5,因此最终跳过了原始的4。结果是您仅删除了所有其他选项。

target.length-10的循环不会出现此问题,因为您在最后将其删除,这对早期元素的索引没有影响。

您还可以使用:

while (target.length > 0) {
    target.remove(0);
}