2016-06-09 2 views
0

나는이 jQuery 코드를 가지고동적으로 버튼

var next = 1; 
$(".add-more").click(function(e){ 
    e.preventDefault(); 
    $(this).replaceWith("<button id='remove" + (next) + "' class='btn btn-danger remove-me pull-right'>-</button>"); 
    var addto = "#field" + next; 
    next = next + 1; 
    var str = "<tr id='field" + next + "'><td><input autocomplete='off' class='input form-control' id='item" + next + "' name='item" + next + "' type='text' data-items='8'/></td>"+ 
       "<td><input autocomplete='off' class='input form-control' id='desc" + next + "' name='desc" + next + "' type='text' data-items='8'/></td>"+ 
       "<td><input autocomplete='off' class='input form-control' id='qty" + next + "' name='qty" + next + "' type='text' data-items='8'/></td>"+ 
       "<td><input autocomplete='off' class='input form-control' id='ucost" + next + "' name='ucost" + next + "' type='text' data-items='8'/></td>"+ 
       "<td><input autocomplete='off' class='input form-control' id='tcost" + next + "' name='tcost" + next + "' type='text' data-items='8'/></td>"+ 
       "<td><input autocomplete='off' class='input form-control' id='type" + next + "' name='type" + next + "' type='text' data-items='8'/></td>"+ 
       "<td><button id='b1' class='btn add-more pull-right' type='button'>+</button></td></tr>"; 
    $(addto).after(str); 
    $("#count").val(next); 
    $('.remove-me').click(function(e){ 
      e.preventDefault(); 
      var fieldNum = this.id.charAt(this.id.length-1); 
      var fieldID = "#field" + fieldNum; 
      $(this).remove(); 
      $(fieldID).remove(); 
    }); 
}); 

코드의이 라인은 여러 필드를 만들 사용자가 할 수 있도록를 생성합니다. 사용자가 "추가"버튼을 클릭하면 여러 필드가 만들어집니다. "추가"버튼이 "제거"버튼으로 변경됩니다. 그리고 다른 "추가"버튼을 추가하십시오.

여기 내 문제는 동적으로 생성 된 # b1 버튼에 이벤트 수신기가 없다는 것입니다. 내가 코드 줄을 사용하려고

,

$("#field" + next).attr('data-source',$(addto).attr('data-source')); 

그러나 그것은 작동하지 않습니다. 내 생각은

http://bootsnipp.com/snippets/featured/dynamic-form-fields-add-amp-remove

누구든지 나를 도울 수, 이와 같은입니까? 동적에 대한

답변

0

요소, 당신은 문서 (또는 페이지로드에서 존재하는 부모 요소)에 이벤트를 추가 한 다음

$(document).on('click', '.add-more', function() {...}; 

대신

$('.add-more').click(... 

이라고 이벤트 위임 사용 생성 인수 (이 경우 '.add-more')로 지정한 하위 항목을 클릭하면 트리거됩니다.