2010-08-11 4 views
1

나는 동적으로 채우는 테이블이 데이터 행이 추가되는 동안 내 테이블 행에 마우스 오버 기능을jquery의 행에 mouseover 이벤트를 추가하려면 어떻게해야합니까?

(mouseover="style.backgroundColor='#E1EBF4'") 

을 추가하고 싶습니다.

function addRecentData(data) { 
    $('#newTable tr:last').after('<tr><td class="name"></td><td class="id"></td></tr>'); 
    var $tr = $('#newTable tr:last'); 
    $tr.find('.name').html(data.Name); 
    $tr.find('.id').html(data.Id); 
} 

답변

3

편집 : 당신이 IE6 지원에 대한 관심을하지 않으면, 당신은 배경을 변경하기 위해 CSS :hover 의사 선택을 사용할 수 참고. 이것은 아마도 첫 번째 고려 사항입니다.

function addRecentData(data) { 
    $('#newTable tr:last').after('<tr><td class="name"></td><td class="id"></td></tr>'); 
    var $tr = $('#newTable tr:last'); 
    $tr.find('.name').html(data.Name); 
    $tr.find('.id').html(data.Id); 
    $tr.mouseover(function() { 
     $(this).css('backgroundColor','#E1EBF4'); 
     // this.style.backgroundColor = '#E1EBF4'; // or you could do this 
    }); 
} 

또 다른 방법 대신 after()inserAfter()를 사용하는 것, 바로 변수를 지정 : 현재 코드 감안할 때

#newTable ​tr:hover { 
    background: #E1EBF4; 
}​ 

, 당신은 테이블에 $tr 참조를 사용할 수 있습니다.

function addRecentData(data) { 
    var $tr = $('<tr><td class="name"></td><td class="id"></td></tr>') 
        .insertAfter('#newTable tr:last'); 
    $tr.find('.name').html(data.Name); 
    $tr.find('.id').html(data.Id); 
    $tr.mouseover(function() { 
     $(this).css('backgroundColor','#E1EBF4'); 
     // this.style.backgroundColor = '#E1EBF4'; // or you could do this 
    }); 
} 

또는 각 <tr>는 마우스 오버를 받아야하는 경우, 당신은 마우스 오버 돌봐하기 위해 #newTable.delegate()를 사용할 수

.

이제 <tr> 요소는 테이블에 추가 될 때 원하는 기능을 자동으로 가져옵니다.

+0

$ (this) .css ('backgroundColor', '# E1EBF4'); 나를 위해 너무 잘 작동하지 않았다. 다른 옵션은 훌륭하게 작동했습니다. 감사! – MrM

1

당신은 jQuery를 통해 이벤트를 추가에 충실해야한다. .live() 이벤트 바인딩 메서드를 사용하여 행을 추가하기 전에 전에 자리에 이벤트 처리기를 배치 할 수 있습니다. 당신이 호버 효과를 원하는 경우 또한, 당신이 jQuery를 이미를 지원하지 않는 브라우저를 제공 mouseenter하는 MouseLeave와 더 낫다 :

$('#newTable tr').live('mouseenter', function() { 
    $(this).css('backgroundColor', '#E1EBF4'); 
}).live('mouseleave', function() { 
    $(this).css('backgroundColor', ''); 
}); 

이것은 또한 바인딩보다 효율적입니다 동적으로 추가 될 때 각 개별 요소에 적용됩니다.

당신이 mouseenter를 사용하고 행을하는 MouseLeave되어 있는지 확인 .live

$('#newTable tr').live('mouseenter', function() { 
    $(this).css('background','#E1EBF4'); 
}).live('mouseleave', function() { 
    $(this).css('background',''); 
}); 

를 사용하기 전에 언급 한 바와 같이

0

마우스 커서를 가져다 대면 /로 마우스 또는 그것은뿐만 아니라와 자식 요소에서 이동할 때 트리거 및하지 않습니다 배경의 깜박임이 앞뒤로 바뀌는 것을 볼 수 있습니다.

관련 문제