2013-02-09 2 views
0

내 스크립트에서 이벤트 (경고)를 발생시키는 데 문제가 있습니다. 내가 잘못하고있는 무슨, 클릭 기능에동적으로 추가 된 링크가 작동하지 않습니다.

$(document).ready(function(){ 

    var i = 1; 

    $('#add').click(function() { 
     $('<div id="d' + i + '" class="fielddiv"><input type="text" class="field" name="dynamic[]" value="' + i + '" /><a href="#" id="remove_question">Cancella</a><hr></div>').fadeIn('slow').appendTo('.inputs'); 
     i++; 
    }); 

    $('#remove_question').on("click", function(event) { 
     alert('dsfsfd'); 
     //$('#d' + $this.attr('todel')).remove(); 
    }); 


    // here's our click function for when the forms submitted 

    $('.submit').click(function(){ 

     var answers = []; 
     $.each($('.field'), function() { 
      answers.push($(this).val()); 
     }); 

     if(answers.length == 0) { 
      answers = "none"; 
     } 

     alert(answers); 

     return false;      
    }); 

}); 

제거 질문 경고를 해고해야하지만, 아무것도, 심지어 오류가 수행되지 않습니다

<div class="dynamic-form"> 
    <form> 
     <div class="inputs"></div> 
     <a href="#" id="add">ADD</a> 
     <input name="submit" type="button" class="submit" value="Submit"> 
    </form> 
</div> 

그리고 JS : 이것은 HTML입니까? 여기에 jsfiddle도 있습니다. 동적으로 추가 요소에 대한

+0

중복 가능성 [동적으로 생성 된 소자에 의해 트리거 이벤트의 이벤트 핸들러에 의해 포착되지 않은 (http://stackoverflow.com/ 질문/12829963/events-triggered-by-dynamic-generated-by-event-hand-by-event-hand) –

+0

@FelixKling, you, again ... :) – gdoron

+0

이벤트 핸들러를 바인딩하기 전에 요소가 존재합니다. 그건 단순히 작동하지 않습니다. 이 문서는 [.on 문서의이 절] (http://api.jquery.com/on/#direct-and-delegated-events)에서 모두 설명합니다. 또한 ID는 고유해야합니다. 두 개의 요소가 동일한 ID를 가질 수는 없습니다. –

답변

2

위임 구문이 있어야합니다. 또한 CLASSES NOT ID를 사용하거나 ID가 중복 될 수 있습니다.

작업 JSfiddle :

http://jsfiddle.net/Z6x8X/2/

번호 :

$(document).ready(function(){ 

    var i = 1; 

    $('#add').click(function() { 
     $('<div id="d' + i + '" class="fielddiv"><input type="text" class="field" name="dynamic[]" value="' + i + '" /><a href="#" class="remove_question">Cancella</a><hr></div>').fadeIn('slow').appendTo('.inputs'); 
     i++; 
    }); 

    $(document).on("click", ".remove_question", function(event) { 
     alert('dsfsfd'); 
     //$('#d' + $this.attr('todel')).remove(); 
    }); 


    // here's our click function for when the forms submitted 

    $('.submit').click(function(){ 

    var answers = []; 
    $.each($('.field'), function() { 
     answers.push($(this).val()); 
    }); 

    if(answers.length == 0) { 
     answers = "none"; 
    } 

    alert(answers); 

    return false; 

    }); 


}); 
0

, 당신은 위임 된 이벤트 핸들러가 필요합니다

$(document).on('click', '#remove_question', function(event) { 
    alert('dsfsfd'); 
}); 

또한, 귀하의 코드로는 동일한 ID와 앵커의 무한한 번호를 추가 할 수있을 것이며, 그 중 하나가 작동하지 않습니다 ID는 고유해야합니다.

관련 문제