香草JavaScript:怎么做 option.remove(Index)有效吗?

问题描述 投票:0回答:3

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

每当更改第一个菜单中的选项时,第二个内容必须更改。

我遵循了两个步骤:

第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中解释概念。

用于故障循环遍历的CODE SNIPPET。

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>
javascript html drop-down-menu html-select
3个回答
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
投票

删除此代码段

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
投票

select中删除元素时,以下所有选项都将重新编制索引。因此,如果你在remove(i)时做i = 3index = 4的选项变成index = 35变成4,依此类推。

然后循环增加i,所以下一次迭代删除4。这是最初5的选项,所以你最终跳过原来的4。结果是您只删除所有其他选项。

target.length-10的循环没有这个问题,因为你最后删除了,这对早期元素的索引没有影响。

你也可以使用:

while (target.length > 0) {
    target.remove(0);
}
© www.soinside.com 2019 - 2024. All rights reserved.