2015-02-04 2 views
0

사용자가 캔버스를 두 번 클릭하면 'tasks'배열에 a를 추가하고 사용자가 생성 된 것을 두 번 클릭하면 배열에서 제거하려고합니다.javascript 배열에 DOM 요소 추가 오류

<script type="text/javascript"> 
    jsPlumb.ready(function() { 
     jsPlumb.Defaults.Container = $('#container'); 
     var tasks = [] 
     var i = 0; 
     $('#container').dblclick(function(e) { 
      var stateId = 'state' + i; 
      var newState = $('<div>').attr('id', stateId).addClass('item'); 
      var title = $('<div>').addClass('title') 
      var stateName = $('<input>').attr('type', 'text') 
      title.append(stateName) 
      stateName.keyup(function(e) { 
       if (e.keyCode === 13) { 
        $(this).parent().text(this.value) 
       } 
      }) 
      stateName.focus(); 
      var connect = $('<div>').addClass('connect'); 
      newState.css({ 
       'top': e.pageY, 
       'left': e.pageX 
      }); 

      newState.append(title); 
      newState.append(connect); 

      $('#container').append(newState); 

      jsPlumb.makeTarget(newState, { 
       anchor: 'Continuous' 
      }); 

      jsPlumb.makeSource(connect, { 
       parent: newState, 
       anchor: 'Continuous' 
      }); 

      jsPlumb.draggable(newState, { 
       containment: 'parent' 
      }); 
      newState.dblclick(function(e) { 

       console.log(tasks) 
       console.log(this) 

       var index = tasks.indexOf(this) 
       alert(index); //ERROR, ALWAYS -1 

//    if (index > -1) { 
//     tasks.splice(index, 1) 
//    } 


       jsPlumb.detachAllConnections($(this)); 
       $(this).remove(); 
       e.stopPropagation(); 

      }); 



      tasks.push(newState) 
//   alert(tasks) 
      i++; 
     }); 

    }); 
</script> 

문제이 라인 :

  var index = tasks.indexOf(this) 
      alert(index); //ERROR, ALWAYS -1 

enter image description here

+0

'this'가 될 것으로 예상되는 것은 무엇입니까? – Johan

+0

@Johan newState – OMGPOP

답변

0

이 시도 :

 newState.dblclick(function(e) { 

      var index = tasks.indexOf(this) 

      if (index > -1) { 
       tasks.splice(index, 1) 
      } 

      jsPlumb.detachAllConnections($(this)); 
      $(this).remove(); 
      e.stopPropagation(); 

     }); 



     tasks.push(newState[0]) 

     i++; 

newState [0] DOM 요소해야 여기 내 구현은 너 찾고있어. newState는 래퍼 jquery 객체입니다