오류/JQuery

JQuery, load() - url 읽어오기 / html 파일 내용 읽어서 보기

greenyellow-s 2024. 8. 27. 16:17
728x90
반응형
HTML
<h1 class="title">동적 드롭다운</h1>
<div class="exec">
	<form>
		<!-- 각 단계별 dropdown을 표시할 span태그 -->
		<span id="category1"></span>
		<span id="category2"></span>
		<span id="category3"></span>
	</form>
</div>

<div class="console"></div>

 

JavaScript
// 파일 로드 1 depth
$('#category1').load('../txt/category-data.html #category1-1', function(){
	$(this).show()
})

//2 depth
$(document).on('change', '#category1 > select', function(){ 
	$('#category2, .console').empty();
	$('#category3').empty();

	//data-target의 속성을 꺼내와라
	var target = $(this).find('option:selected').attr('data-target');
	console.log('target = ' + target);

	$('#category2').load('../txt/category-data.html' + target, function(){
		$(this).show();
	})
})

오류

 

#category1을 select 하면 


아래 구문으로 인해 #category2, #category3, .console의 내용이 비워지고

$('#category2, .console').empty();
$('#category3').empty();

 

 

#category2에 클릭한 option의 data-target 속성을 가져와

var target = $(this).find('option:selected').attr('data-target');

 

 

해당 태그를 보여줘야되는데

$('#category2').load('../txt/category-data.html' + target, function(){
	$(this).show();
})

 

 

 

오류 : 모든 #category1,2,3 모든 태그의 option이 다 출력된다.


이유

 

url 주소에 태그를 같이 보낼때는 주소와 태그 사이에 띄어쓰기로 구분지어줘야 한다.

붙여서 보내면 태그까지 주소로 인식해버린다.

 

따라서, html 뒤에 띄어쓰기를 해줘야 한다.


오류 해결
$('#category2').load('../txt/category-data.html ' + target, function(){
728x90
반응형

'오류 > JQuery' 카테고리의 다른 글

JQuery, Checkbox 전체 선택/해제  (1) 2024.08.26