InsertBefore()无法与variable.insertBefore()一起正常使用

时间:2019-09-01 17:55:55

标签: javascript

我是js的新手,我对这段代码有麻烦,我已经尝试将其修复5个多小时,但没有成功,有人能找到我所缺少的吗?

这是我的代码:

function MaterialCreator(materialid, materialNo, thumb , sofaimgboxxx, materialqty){

parentidmaterial = "";
for(i = 1; i < materialqty; i++){

  var newDiv = document.createElement("div"); 
  newDiv.innerHTML = "No. "+ i;
  newDiv.id = thumb;
  newDiv.className = "MaterialSidemenuHorizontal";
  newDiv.style = "background-image: url(/sofaplanner/img/colors/0"+ materialNo +"/0"+ thumb +".png)";
  newDiv.setAttribute("onclick", "javascript:colorFilter(this.id, " + sofaimgboxxx + ")"); 
  thumb = thumb + 1;

 var currentDiv = document.getElementById(materialid); 
 parentidmaterial = document.getElementById(materialid).parentNode.id;

 if(parentidmaterial = "choosematerialInnervs"){choosematerialInnervs.insertBefore(newDiv, currentDiv);}
 else if(parentidmaterial = "choosematerialInnernp"){choosematerialInnernp.insertBefore(newDiv, currentDiv); }
 else if(parentidmaterial = "choosematerialInnerrg"){choosematerialInnerrg.insertBefore(newDiv, currentDiv); }
 else if(parentidmaterial = "choosematerialInnertr"){choosematerialInnertr.insertBefore(newDiv, currentDiv); }
 else if(parentidmaterial = "choosematerialInnerrz"){choosematerialInnerrz.insertBefore(newDiv, currentDiv); }
 
}}
<!-- TR - MATERIAL 04 -->
<div id='choosematerialInnertr' class="choosematerialInner">
	<div class="sidemenuTitle">左アーム 生地 TR</div>
	<div id="materialauto4"></div>
			<script>
			document.addEventListener('DOMContentLoaded', (event) => {
			MaterialCreator("materialauto4", 4, 401, "sofa-img-box1img", 23);})
			</script>
</div>

<!-- RZ - MATERIAL 05 -->
<div id='choosematerialInnerrz' class="choosematerialInner">
		<div class="sidemenuTitle">左アーム 生地 RZ</div>
		<div id="materialauto5">
		<script>
			document.addEventListener('DOMContentLoaded', (event) => {
			MaterialCreator("materialauto5", 5, 501, "sofa-img-box1img", 7);})
		</script>
</div>

我想直接通过insertBefore使用变量“ parentidmaterial”(它包含父ID的结果),但是由于某种原因,它仅在我实际输入变量结果的情况下才对变量起作用,所以我尝试了带有if,但现在仅适用于第一种材料,所有其他材料均未找到Node错误

parentidmaterial.insertBefore(newDiv, currentDiv)

1 个答案:

答案 0 :(得分:2)

看来您的状况有问题,

如果使用if语句,则应为“ ==”而不是“ =”(赋值)

if(parentidmaterial == "choosematerialInnervs"){choosematerialInnervs.insertBefore(newDiv, currentDiv);}
 else if(parentidmaterial == "choosematerialInnernp"){choosematerialInnernp.insertBefore(newDiv, currentDiv); }
 else if(parentidmaterial == "choosematerialInnerrg"){choosematerialInnerrg.insertBefore(newDiv, currentDiv); }
 else if(parentidmaterial == "choosematerialInnertr"){choosematerialInnertr.insertBefore(newDiv, currentDiv); }
 else if(parentidmaterial == "choosematerialInnerrz"){choosematerialInnerrz.insertBefore(newDiv, currentDiv); }