2010-07-30 1 views
2

idinputDataElementstable에 동적으로 input 개의 요소를 추가하고 있습니다.jQuery를 사용하여 동적으로 추가 된 입력 HTML 요소에서 mouseover 이벤트를 캡처하는 방법은 무엇입니까?

function renderInputDataRows(inputData) {                                                             
    var rows = "";                                                                   
    for (var i = 0; i < inputData.length; i++) {                                                           
     rows += '<tr>' +                                                                
      // ... 
      '<td class="rowActions">' + \ 
      '<input type="image" ' + \ 
      '  style="position:relative; ' + \ 
      '    bottom:-2px; ' + \ 
      '     left:-4px; ' + \ 
      '  padding-right:2px;" ' + \ 
      '  src="images/delete.png" ' + \ 
      ' onClick="deleteInputDataRow(' + inputData[i].index + ');"' + \ 
      '  name="deleteAction" ' + \ 
      '  value="deleteInputDataRow' + inputData[i].index + '"' + \ 
      '  size="18,18" ' + \ 
      ' border="0" />' + \ 
      '</td>' + 
      // ...                                                            
      '</tr>';                                                                 
    }                                                                      
    return rows;                                                                   
}  

질문 :

input 요소는 이름 deleteAction이 나는 ​​deleteAction -named input 요소 mouseover 이벤트를 캡처하고 싶습니다.

$(document).ready(function() { 
    inputDataElementsRowDeleteActions = $("#inputDataElements input:[name=deleteAction]"); 
    ... 
    inputDataElementsRowDeleteActions.mouseover(function(event) { 
     alert(event); 
    }); 
}); 

문제 :

나는 다음과 같은 jQuery를 스크립트가 나는 input 요소 마우스를 움직일 때 나는 alert 메시지가 없습니다.

요소가 동적으로 추가 될 때 mouseover 이벤트를 jQuery로 캡처하는 방법이 있습니까?

답변

4

가장 간단한 방법은 .live()

inputDataElementsRowActions.live('mouseover', function(event) { 
    alert(event); 
}); 

을 사용하는 것입니다하거나 유사한 (아마이 경우 선호)입니다 .delegate()를 사용할 수 있습니다.

$("#inputDataElements").delegate('input[name=rowAction]', 'mouseover', function(event) { 
    alert(event); 
}); 

이들은 둘 다 거품을 일으키는 이벤트를 캡처하여 작동합니다. .live()은 루트에서 캡처하고, .delegate()은이 경우 #inputDataElements에서 캡처합니다.

  • http://api.jquery.com/delegate/
  • http://api.jquery.com/live/
    • 그렇지 않으면, 당신은 이벤트를 결합 할 것이다 (이후에) 당신은 요소를 만들 수 있습니다.

    +0

    감사합니다. 완벽하게 작동합니다. –

    +0

    델리게이트는 언제 선호되지 않습니까? – redsquare

    +0

    @redsquare - DOM의 어느 부분에 요소가 추가 될지 알 길이 없다고 생각합니다. 그것은 내가 상상할 수있는 드문 경우입니다. '.live()'는 제 의견으로 남용되었습니다. – user113716

    관련 문제