动态添加的元素函数调用不起作用

时间:2016-09-11 09:51:34

标签: javascript jquery html

当动态添加元素时,我遇到函数调用的问题。 Here是代码笔示例的链接。函数调用 - onclick - 来自此按钮:

<button id="btnFocus" class="btnFocus"  onclick="focusToDIV($(this))">Focus to DIV</button>

功能focusToDIV:

 var focusToDIV = function(btnReference){        
  btnReference.parent().find("#div3").focus();       
}

静态添加包含此按钮的第一个元素。所有其他元素都可以添加按钮&#39;添加新的&#39;。使用静态添加元素函数调用focusToDIV并且div3获得焦点。

使用动态添加的元素,未定义btnReference,这就是抛出此错误的原因:

  

未捕获的TypeError:无法读取属性&#39; parent&#39;未定义的

如何通过动态添加元素使此功能正常工作(通过点击btnFocus将焦点放在div3上)?为什么没有定义btnReference,如果将元素动态添加到DOM?

&#13;
&#13;
var focusToDIV = function(btnReference){  
  btnReference.parent().find("#div3").focus();    
}


var addNew = function(){
  
  $("#divMain").append("<div class='divContainer' class='divContainer'> <div id='divInner' class='divInner'>" +
    "<div id='div2' class='div2'> <div id='div3' class='div3' contentEditable='true'></div>" +
    "</div></div>  <button id='btnFocus' class='btnFocus'  onclick='focusToDIV($(this))'>Focus to DIV</button>    </div>");
  
  
}




  
  
&#13;
.divMain{
  height: 100vh;
  width: 100vw;
}

.divContainer{
  position: relative;
  display: inline-block;
  left: 20%;
  top: 10%;
}

.divInner{  
  width: 300px;
  height: 300px;
  border: 1px solid black;
}

.div2{
  position: relative;
  left: 20px;
  top: 20px;
  width: 200px;
  height: 100px;
  border: 1px solid blue;
}

.btnFocus{
  position: absolute;
  top: 305px;
  
}

.div3{
  position: relative;
  left: 10%;
  top: 10%;
  width: 150px;
  height: 80px;
  border: 1px solid red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="divMain" class="divMain">
  
  <button id="btnAdd" onclick="addNew()">Add new</button>
  
  <div class="divContainer" class="divContainer">
  <div id="divInner" class="divInner" >
    <div id="div2" class="div2">
      <div id="div3" class="div3" contentEditable="true"></div>    
    </div>     
  </div>  
  <button id="btnFocus" class="btnFocus"  onclick="focusToDIV($(this))">Focus to DIV</button>
    
  </div><!-- divContainer -->
  
  
</div><!-- divMain -->
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您需要将onclick方法从focusToDIV()更改为focusToDIV($(this))

由于元素未通过,因此btnReference未定义,并且您正在调用该未定义变量的方法。

var addNew = function(){

  $("#divMain").append("<div class='divContainer' class='divContainer'> <div id='divInner' class='divInner'>" +
    "<div id='div2' class='div2'> <div id='div3' class='div3' contentEditable='true'></div>" +
    "</div></div>  <button id='btnFocus' class='btnFocus'  onclick='focusToDIV($(this))'>Focus to DIV</button>    </div>");


}