jquery innerHTML 사용 주의

문제 코드:
먼저 다음 코드 를 보십시오.
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
	<head>
		<meta content="text/html;charset=utf-8" http-equiv="content-type" />
		<script src="jquery-1.3.2.js" type="text/javascript">
		</script>
		<style type="text/css">
			#inner {
				margin:0 auto;
				width:150px;
				height:50px;
				border:1px solid green;
			}
		</style>
		<script type="text/javascript">
		$(function(){
			$("#inner").click(function(){
				//  ,      
				$("#test")[0].innerHTML="";
				
				//    
				//$("#test").empty();
			});
			
		});
		</script>
		<title>  </title>
	</head>
	<body>
		<div style="height:500px;width:500px;border:1px solid red;padding-top:100px;" id="test">
			<div id="inner">click to remove me</div>
		</div>	
	</body>
</html>

 
 
필드:
inner div 는 흔히 볼 수 있 는 ajax 가 서버 에서 동적 으로 구 조 된 요 소 를 사용 하거나 세 션 html 를 주입 할 수 있 습 니 다. 효 과 는 inner 를 클릭 한 후에 그것 과 그의 형 제 를 제거 하 는 것 입 니 다. 전통 적 인 사고 에 따라 직접 inner HTML = "" 좋 습 니 다. 요 소 를 삭제 하 는 모든 사건 감청 기 를 생각 할 수 있 습 니 다. 그러나 ie6 를 제외 하고(메모리 유출 을 일 으 키 는) 이외 의 브 라 우 저 는 이벤트 모니터 를 제거 하 는 것 이 필요 하지 않 습 니 다.
jquery 메커니즘:
그러나 확실한 것 은 jquery 에서 innerHTML 방법 으로 요 소 를 비 우 는 것 입 니 다. 반드시 메모리 가 유출 될 수 있 습 니 다. jquery 는 같은 요소 의 다 중 이벤트 처리 에 대해 브 라 우 저 이벤트 모델 을 직접 사용 하지 않 고 자신의 캐 시 사건 을 사용 하여 트리거 를 옮 겨 다 니 며 trigger 프로그램 이 촉발 하기 쉽 기 때 문 입 니 다.
 
// Init the element's event structure
		var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
			handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
				// Handle the second event of a trigger and when
				// an event is called after a page has unloaded
				return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
					jQuery.event.handle.apply(arguments.callee.elem, arguments) :
					undefined;
			});
 
data 방법 을 사용 하여 일부 데 이 터 를 요소 에 연결 시 켰 습 니 다. 상기 사건 은 바로 이 시스템 캐 시 이벤트 모니터 를 사용 하 는 것 입 니 다.
그러면 알 수 있 듯 이 직접 innerHTML = "" jquery 에 게 요소 와 관련 된 데 이 터 를 삭제 하 라 고 알 리 지 않 으 면 이 부분 데 이 터 는 더 이상 방출 되 지 않 습 니 다. 즉, 메모리 유출 입 니 다.
해결:
jquery 는 이러한 측면 을 생각 했 습 니 다. empty 함 수 를 제 공 했 습 니 다. 그 사상 은 노드 의 모든 아들, 손, 중 손... 노드 ($("*", this) 를 먼저 비우 고 노드 의 삭 제 를 하 는 것 입 니 다.
 
remove: function( selector ) {
		if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
			// Prevent memory leaks
			jQuery( "*", this ).add([this]).each(function(){
				jQuery.event.remove(this);
				jQuery.removeData(this);
			});
			if (this.parentNode)
				this.parentNode.removeChild( this );
		}
	},

	empty: function() {
		// Remove element nodes and prevent memory leaks
		jQuery(this).children().remove();

		// Remove any remaining nodes
		while ( this.firstChild )
			this.removeChild( this.firstChild );
	}
 
 

좋은 웹페이지 즐겨찾기